简体   繁体   English

如何基于Entity Framework代码优先模型自动生成.mdf db(如果不存在)

[英]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.

相关问题 先在Entity Framework代码中自动生成存储过程 - Generate stored procedures automatically in Entity Framework code-first 如何从Entity Framework 4.3代码优先模型生成DDL脚本? - How can I generate DDL scripts from Entity Framework 4.3 Code-First Model? 如何在实体框架代码优先中创建具有自引用的模型? - How to create a model with self reference in Entity Framework Code-First? 实体框架代码首先为模型上不存在的属性生成数据库列 - Entity framework code first generates DB column for property that does not exist on the model 实体框架代码优先迁移不生成外键并忽略 ForeignKey 数据注释 - Entity Framework code-first migrations does not generate a foreign key and ignores the ForeignKey data annotation 为什么实体框架代码优先(使用现有数据库)继续尝试从EdmMetadata表获取数据? - Why does Entity Framework Code-First (with an existing DB) keep trying get data from an EdmMetadata table? 如何在实体框架中从模型优先改为代码优先 - How to change from Model-first to Code-First in Entity Framework Entity Framework代码优先:如何在模型上添加更多道具并更新数据库? - Entity Framework code-first : how to add more props on model and update database? 如何使用实体框架代码优先使用较新的数据库模型版本 - How to use Entity Framework code-first with a newer database model version 如何使用Entity Framework代码优先对“共享”进行建模-多对多是对的吗? - How to model “sharing” with Entity Framework code-first - is many-to-many right?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM