简体   繁体   English

通过Entity Framework 6 + MySQL的代码设置数据库创建/迁移

[英]Set up database creation/migrations from code for Entity Framework 6 + MySQL

I've previously used NHibernate and Fluent Migrator in projects to create a database (if it didn't already exist) and update the schema through migration scripts. 我以前在项目中使用过NHibernate和Fluent Migrator来创建数据库(如果尚不存在)并通过迁移脚本更新架构。 I'm looking over Entity Framework (6) to do a comparison and I'm having trouble replicating that functionality. 我正在查看Entity Framework(6)进行比较,但无法复制该功能。

In my App.config , I've set up my connection string and db providers. 在我的App.config ,我设置了连接字符串和数据库提供程序。 I then went ahead and created a data model that I would like to be represented as a table in the database. 然后,我继续创建了一个数据模型,希望将其表示为数据库中的表。

namespace DataModels
{
    public class StoreClient
    {
        public int Id;
        public string DisplayName;

        public StoreClient()
        {
        }
    }
}

I then went ahead and created a database context. 然后,我继续创建数据库上下文。

namespace DataModels
{
    public class StoreContext : DbContext
    {
        public DbSet<StoreClient> StoreClients { get; set; }
    }
}

On service start I created an instance of StoreContext and tried to add and call db.SaveChanges(); 在服务启动时,我创建了一个StoreContext实例,并尝试添加并调用db.SaveChanges(); , but this is failing because there is no schema that matches my StoreClient. ,但这失败了,因为没有与我的StoreClient相匹配的架构。

My question is simple. 我的问题很简单。 How do I configure my StoreContext (or EF in general) to automatically create my database schema, and how do I set it up to migrate when I make changes to that schema? 如何配置StoreContext (或通常的EF)以自动创建数据库架构,以及如何在更改该架构时将其设置为迁移?

This seems simple, but my searching around hasn't gotten me anything that looks remotely familiar coming from the NHibernate world. 这看起来很简单,但是我周围的搜索并没有给我任何来自NHibernate世界的看起来很熟悉的东西。

If you want your db to be created automatically try to put some code in your Application_Start() method. 如果要自动创建数据库,请尝试在Application_Start()方法中放入一些代码。 for example: 例如:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, Configuration>());
StoreContext context = new StoreContext();
context.Database.Initialize(true);

Where Configuration class is created upon automatic migrations are enables in the console. 在控制台中启用在自动迁移时创建Configuration类的位置。 Check out this msdn demo . 查看此msdn 演示 Also i am not shure that your code firs model will work that way. 另外我也不保证您的代码冷杉模型会那样工作。 If not try changing your fields with properties. 如果没有,请尝试使用属性更改字段。

namespace DataModels
{
    public class StoreClient
    {
        public int Id { get; set; }
        public string DisplayName { get; set; }
        public StoreClient()
        {
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM