EF Core代码优先是指根据实体类和DbContext的配置来创建数据库,代码优先方法一般开始一个新项目时对数据库没有清晰了解的情况下非常有用,EF Core 使用migration命令来完成数据库和表的创建
为了理解Code-First模式如何工作,我们创建一个ASP.NET Core 项目并安装Entity Framework Core 包,这个项目中我们使用Company数据库.
1 创建 Entity & DbContext
namespace EFCoreCodeFirst.Models
{
public class Information
{
public int Id { get; set; }
public string Name { get; set; }
public string License { get; set; }
public DateTime Establshied { get; set; }
public decimal Revenue { get; set; }
}
}
namespace EFCoreCodeFirst.Models
{
public class CompanyContext:DbContext
{
public CompanyContext(DbContextOptions<CompanyContext> dbContextOptions)
:base(dbContextOptions)
{
}
public DbSet<Information> Information { get; set; }
}
}
我们注册DbContext服务在Program类,添加下面代码:
builder.Services.AddDbContext<CompanyContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
在appsettings.json 文件添加ConnectionString连接字符串
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Company;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
}
2 EF Core Migrations
在Visual Studio,通过如下菜单Tools->NuGet Package Manager->Package Manager Console (PMC),在PMC中输入下列命令:
add-migration CompanyDB
我们也可以用CLI命令来完成这个工作:
dotnet ef migrations add CompanyDB
执行上面命令将会在项目中创建Migrations文件
update-database
也可以使用CLI命令来完成相同工作
dotnet ef database update
执行这个命令会创建数据库,我们在Visual Studio中打开SQL Server Object Explorer 窗体
3 新增数据
让我们在Information表中使用EF Core创建一条记录,添加一个新的方法在Controller中用来新增数据,代码如下:
public class HomeController : Controller
{
private CompanyContext context;
public HomeController(CompanyContext cc)
{
context = cc;
}
public IActionResult CreateInformation()
{
var info = new Information()
{
Name = "YogiHosting",
License = "XXYY",
Revenue = 1000,
Establshied = Convert.ToDateTime("2014/06/24")
};
context.Entry(info).State = EntityState.Added;
context.SaveChanges();
return View();
}
}
4 Entity Framework Core 种子数据
我们创建数据库并且通过代码填充测试数据,我们称之为种子数据,在应用程序的Data目录创建一个新的静态类DbInitializer,Initialize方法将测试数据插入到数据库中:
public static class DbInitializer
{
public static void Initialize(CompanyContext context)
{
// Look for any students.
if (context.Information.Any())
{
return; // DB has been seeded
}
var infos = new Information[]
{
new Information { Name = "YogiHosting", License = "XXYY", Revenue = 1000, Establshied = Convert.ToDateTime("2014/06/24") },
new Information{ Name ="Microsoft", License ="XXXX", Revenue = 1000, Establshied = Convert.ToDateTime("2014/07/14") },
new Information{ Name ="Google", License ="RRRRR", Revenue = 1000, Establshied = Convert.ToDateTime("2019/06/18") },
new Information{ Name ="Apple", License ="XADFD", Revenue = 1000, Establshied = Convert.ToDateTime("2022/02/02") },
new Information{ Name ="SpaceX", License ="##@$", Revenue = 1000, Establshied = Convert.ToDateTime("2030/10/01") }
};
context.Information.AddRange(infos);
context.SaveChanges();
}
}
在我们应用程序Program类中调用该方法:
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<CompanyContext>();
context.Database.EnsureCreated();
DbInitializer.Initialize(context);
}
EnsureCreated 方法负责在没有数据库的情况下创建数据,调用DbInitializer.Initialize(context)会将测试数据插入到数据库中
总结