Accepted Answer

You must do two actions in order to use code first with an existing database: Set your connection string and disable the database initialization strategy, respectively. The following context sample demonstrates how to accomplish those two goals:

public class ApplicationDbContext : DbContext
    public ApplicationDbContext()
        : base("ConnectionStringName")

    // DbSets here

Entity Framework now presumes that your table names are pluralized versions of the entity class names by convention. You can use the entity class name if the table name is not plural or is different from the entity class name.Table property to explain what it should be in detail:

public class Foo
    // properties

Similarly, if the names of your columns and properties don't match, you can utilize theColumn a property to identify those

public string Foo { get; set; }


When I first read this, I didn't notice that you're attempting to combine already-existing tables with tables created by code. This cannot be done. Since using an existing database and existing tables necessitates turning off the initialization technique, either every table in that database must already exist or Entity Framework must create every table. There is no halfway.

You need two databases and two contexts: one where EF will generate everything via code first and the other where the initialization strategy is off and you are in charge of the database and tables if you need to use certain existing tables and have EF construct some. This is significant since it allows you to combine and match things. All of your code first entities must not explicitly or implicitly relate to any of your already-existing database entities via navigation properties; otherwise, EF will create the tables and add all of your code first entities to the context.

The best you can hope for is to have a normal property that stores the id of the connected object, and then manually look for the entity using this id from the current database context. In other words, it won't be a genuine foreign key, and lazy-loading and other features won't be available.

2/24/2016 3:40:10 PM

Popular Answer


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow