.net framework , code first

时间:2023-03-09 00:29:31
.net framework , code first

1. 创建一个控制台应用程序, 并添加引用

.net framework , code first

2 创建 一个类

public class New
{
[Key]
public string NewId { get; set; }
public string Title { get; set; }
}

3 创建一个类继承 DbContext

 public class NewContext : DbContext
{
public NewContext()
{
System.Diagnostics.Debug.Write(Database.Connection.ConnectionString);
}
public DbSet<New> News { get; set; }
}

4 config 文件配置 ConnectionString

<add name="NewContext" connectionString="Data Source=.;Initial Catalog=CodeFirstTest;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

5 在Main 方法中调用

 using (var db = new NewContext())
{
Console.Write("start");
Console.OutputEncoding = Encoding.GetEncoding(); var newModel = new New { NewId = Guid.NewGuid().ToString(), Title = "sdfdsfdsfdsf" };
db.News.Add(newModel);
db.SaveChanges();
foreach (var n in db.News)
{
Console.WriteLine(n.Title);
}
Console.Write("success");
Console.ReadKey();
}