Is it possible to mix database first and code first models with entity framework?

asp.net, asp.net-mvc, c#, entity-framework

Solution

Technically, it's possible, but I wouldn't recommend it. It's far better to just use code-first across the board. Yes, ironically, you can use "code-first" with an existing database.

Just create POCOs that match the tables in your existing database. If your POCO is not named the same as your table (not all table names would be valid or appropriate class names), you can use the `Table` attribute to explicitly tell EF what table your POCO works with:

[Table("SomeTable")]
public class MyAwesomeEntity
{
    ...
}

Then, you'll need a separate context specifically for this existing database and any entities that belong to it. All you have to do is 1) tell it what connection string it should use and 2) turn off database initialization, so EF doesn't try to actually create the database.

public MyExistingDatabaseContext : DbContext
{
    public MyExistingDatabaseContext()
        : base("MyExistingDatabaseConnectionStringName")
    {
        Database.SetInitializer<MyExistingDatabaseContext>(null);
    }

    // DbSets here
}

And that's it. Whenever you need to work with an entity from this existing database, just new up this context or get it some other way, such as through a DI (dependency injection) container, and go to town.

Problem

I am about to begin a web application where I would like to use the Entity Framework with (mostly) code first models. However, in addition to the application-specific models I plan to create, I have to use an external user database. Is it possible to specify one of my models as database first and to use a separate database context?

Original source