.NET Core Entity Framework Core 创建数据库

发布时间 2023-08-29 11:13:36作者: 糯米白白

自动创建数据库必须在NuGet 中安装一下EFCore库

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

数据迁移常用命令

dotnet ef migrations add NewColum --新增migrations
dotnet ef database update--跟新数据库
dotnet ef migrations add Addrs--新增一个migrations
dotnet ef database update
dotnet ef datebase update NewColum--根据newcolum跟新数据库
dotnet ef migrations remove--删除最新未使用的migrations

1、.NET Core中手动执行命令创建

dotnet ef migrations add MyFirstMigration
dotnet ef database update

2、通过.NET Core代码,首次使用时自动创建

获取context

string connectionString = "数据库链接字符串";

var builder = new DbContextOptionsBuilder<CustomDbContxt>()
    .UseSqlServer(connectionString);

var context = new CustomDbContxt(builder.Options);

1)如果已经创建了迁移,则可以使用:

context.Database.Migrate();

使用添加迁移的表和数据创建数据库

2)如果不迁移数据,只是需要在首次运行时,则可以使用:

context.Database.Migrate();

3)如果需要检查数据库是否存在,则可以使用:

bool exists = (context.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists();

4)如果需要删除数据库,则可以使用:

context.Database.EnsureDeleted();