简体   繁体   中英

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. I'm looking over Entity Framework (6) to do a comparison and I'm having trouble replicating that functionality.

In my App.config , I've set up my connection string and db providers. 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(); , but this is failing because there is no schema that matches my 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?

This seems simple, but my searching around hasn't gotten me anything that looks remotely familiar coming from the NHibernate world.

If you want your db to be created automatically try to put some code in your Application_Start() method. 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. Check out this msdn demo . 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()
        {
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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