EF Migrations for Database-first approach?

♀尐吖头ヾ 提交于 2019-11-29 05:24:27
Paul

As far as I know, EF Migrations is a product targeted at CodeFirst and doesn't support Database First operations.

CodeFirst assumes that you will never make any changes manually to the database. All the changes to the database will go through the code first migrations.

I think there is! You need to continue your way through the code first.

To do this, Suppose that you have the following DbContext that EF Db first created for you:

public class MyDbContext : DbContext
{
    public MyDbContext()
        : base("Name=DefaultConnection")
    {

    }

    // DbSets ...
}

change that to the following to start using code first and all magic tools of it (migration, etc.):

public class MyDbContext : DbContext
{
    public MyDbContext()
        : base("YourDbFileName")
    {

    }

    // DbSets ...
}

It causes that EF creates a new connection string using SQL Express on your local machine in your web.config file with the name YourDbFileName, something just like the early DefaultConnection Db first created.

All you may need to continue your way, is that edit the YourDbFileName ConStr according to your server and other options.

More info here and here.

Starting Entity Framework 4.1 you can do Code First Migrations with an existing database.

So first you have the database, create the model, enable migrations.

The most important thing to remember that you should run Enable-Migrations before you do any changes to the schema since it should be in sync between your db and code.

Just look for your DbContext child object and look for this method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

If you comment this:

throw new UnintentionalCodeFirstException();

then the exception would not be thrown on migration operation. As you might imagine, the migration look for this part to know what are the configurations for each entity with what table or tables.

Sorry if I didn't go with more details, if you wish more, I'll be happy to edit this and make it better!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!