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?
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.
You should use the code first from database option if you already have an existing database available but want to use code first.
1) In your Models folder, right click on Add, New item,
2) Select ADO.NET Entity Data Model in the Data tab.
3) Enter a model name,
4) Select Code First from database.
5) Select connection string,
6) Choose your database objects you want to include in your model.
You don't have to write the code for the context and model from scratch because it will generate the classes for you.