[英]How to automatically generate .mdf db if it does not exist based on Entity Framework code-first model
I have written the models and context class, successfully ran the initial migration and seeded and generated the local database on my machine. 我已经编写了模型和上下文类,成功运行了初始迁移,并在我的机器上播种并生成了本地数据库。 The problem is I am working on a collaborative project at University using Github and the
.gitignore
file ignores .mdf
files (for obvious reasons). 问题是我正在使用Github在大学合作项目中,
.gitignore
文件忽略了.mdf
文件(出于明显的原因)。
My question: is there a way to automatically generate and seed the .mdf
SQL Server database file on app start-up if it doesn't exist in the App_Data
folder? 我的问题:如果
App_Data
文件夹中不存在.mdf
SQL Server数据库文件,是否可以在应用程序启动时自动生成该文件并将其种子化?
My context class looks like this: 我的上下文类如下所示:
public class ABFContext : DbContext
{
public ABFContext() : base("ABFDatabase")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<ABFContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<BasketItem> BasketItems { get; set; }
public DbSet<Catalogue> Catalogues { get; set; }
// other entities omitted for clarity
}
Connection string like this: 像这样的连接字符串:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ABF-20190304080703.mdf;Initial Catalog=aspnet-ABF-20190304080703;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Migrations config with seed data: 带有种子数据的迁移配置:
internal sealed class Configuration : DbMigrationsConfiguration<ABF.DAL.ABFContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ABF.DAL.ABFContext context)
{
context.CustomerRoles.AddOrUpdate(x => x.Id,
new CustomerRole() { Id = 1, Role = "Member - Current" },
new CustomerRole() { Id = 2, Role = "Member - Previous" },
new CustomerRole() { Id = 3, Role = "Customer" },
new CustomerRole() { Id = 4, Role = "Sponsor" },
new CustomerRole() { Id = 5, Role = "Staff/Volunteer" }
);
// other seed data omitted for clarity
}
}
On EF 6: Use Database.SetInitializer method. 在EF 6上:使用Database.SetInitializer方法。 (Untested code)
(未经测试的代码)
class MyInitializer : IDatabaseInitializer<MyContext>
{
public void InitializeDatabase(MyContext context)
{
if (context.MyEntities.Any()) return;
// add entities here
}
}
class MyContext : DbContext
{
public MyContext()
{
Database.SetInitializer(new MyInitializer());
}
}
SetInitializer doc: https://docs.microsoft.com/en-us/previous-versions/visualstudio/gg679461(v=vs.113) SetInitializer doc: https ://docs.microsoft.com/zh-cn/previous-versions/visualstudio/gg679461(v = vs.113 )
IDatabaseInitializer doc: https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.idatabaseinitializer-1?view=entity-framework-6.2.0 IDatabaseInitializer doc: https ://docs.microsoft.com/zh-cn/dotnet/api/system.data.entity.idatabaseinitializer-1 ? view = entity-framework-6.2.0
I was able to achieve this by adding Database.Initialize(true);
我能够通过添加
Database.Initialize(true);
来实现这一点Database.Initialize(true);
to the context class: 到上下文类:
public class ABFContext : DbContext
{
public ABFContext() : base("ABFDatabase")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<ABFContext>());
Database.Initialize(true);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<BasketItem> BasketItems { get; set; }
public DbSet<Catalogue> Catalogues { get; set; }
}
Modifying the connection string to: 将连接字符串修改为:
<add name="ABFDbConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
And running the update-database
EF command in the package manager console. 并在程序包管理器控制台中运行
update-database
EF命令。 This seeded and generated the .mdf
SQL Server database file on a different machine using the same code-first model. 这使用相同的代码优先模型在另一台计算机上播种并生成了
.mdf
SQL Server数据库文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.