我第一次尝试使用Entity Framework从头开始创建Web应用(.net core 2.1)。由于某种原因,我无法生成数据库。
所以我安装了EF nuget。并做了接下来的事情:
添加了来自DbContext的类:
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Server> Servers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Server>().HasData(
new Server
{
Name = "My Server",
InUse = false
}
);
}
}
并创建实体:
public class Server
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public bool InUse { get; set; }
}
在startup.cs中的ConfigureServices方法中,我添加了:
var connectionString = Configuration.GetConnectionString("ApplicationConnection");
services.AddDbContext<ApplicationDbContext>
(options => options.UseSqlServer(connectionString));
来自于appsettings的连接字符串,我对其进行了调试,使其通过,并且与其他项目中使用的字符串相同,只是数据库名称值不同,应该可以。
我还从控制台的Add-Migration命令运行,所以我获得了包含InitialCreate迁移和一些快照文件的Migrations文件夹。
但是,当我运行应用程序时,我没有收到任何错误,但它从未在InitialCreate.cs迁移内达到断点,因此也从未创建数据库。
有什么想法应该在什么地方触发什么?
答案 0 :(得分:0)
如果您想要实体框架自动创建数据库
在配置文件中,将此行添加到构造函数中:
AutomaticMigrationsEnabled = true;
然后将代码添加到DBContext:
Database.SetInitializer(new
DropCreateDatabaseAlways<YourDbContext>());
然后在应用程序已经运行时:
Database.SetInitializer(new
DropCreateDatabaseIfModelChanges<YourDbContext>());
您还可以看看MigrateDatabaseToLatestVersion
如果您手动跟踪数据库的版本:
更新AutomaticMigrationsEnabled = false;
从控制台运行命令Update-Database
迁移数据库
手动
答案 1 :(得分:0)
因此,我能够通过在Configure()方法中的Startup.cs中添加下一个代码来创建数据库
using (var scope = app.ApplicationServices.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.Migrate();
if (!dbContext.Servers.Any())
{
dbContext.Servers.Add(new Server
{
Name = "My Server",
InUse = false
});
dbContext.SaveChanges();
}
}