Entity Framework Code First with Existing Database

Rowan Miller over at the ADO.NET Blog announced on Tuesday that the next release of Entity Framework, version 7, will do away with EDMX and the associated visual designer. There was much groaning and gnashing of teeth across the interwebs, not out of love for EDMX, but ironically, out of confusion that this was in effect removing the ability to work with existing databases. I still find it amazing after all this time that so few know that you can actually use code first with an existing database (despite the seemingly contradictory name). Rowan, in fact, addresses the naming in his post:

In EF4.1 we introduced Code First. Understandably, based on the name, most folks think of Code First as defining a model in code and having a database generated from that model. In actual fact, Code First can be used to target an existing database or generate a new one.

So, here, folks, is exactly how that's done. Just as if you were actually using code first to generate a new database, you model your existing tables using POCOs. In code first, the convention is for the table name to be a pluralized version of the class name (Foo => dbo.Foos). If your table name doesn't match that convention, you just need to decorate your class with the Table attribute to tell it which table to attach to. For example:

[Table("foobar")]
public class Foo
{
    ...
}

Easy enough. Once you have your entities mapped out. You create a subclass of DbContext, where you'll 1) tell it exactly what database to use (via connection string) and 2) turn off its database initialization strategy. The latter prevents EF from attempting to create the database or generate migrations.

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

    // DbSets here
}

And, that is literally it. You now have Code First-style POCOs tied to an existing database, without an EDMX file in sight. But wait, there's more. The EF Power Tools Visual Studio extension can be installed to give you the ability to actually generate all of this directly from your existing database. Yep, that's right, you get all the POCOs and a fully working context all without touching a line of code and still no forsaken EDMX file. So, I think it's great that EF 7 will kill the EDMX once and for all, but there's no need to wait. This all can be done in any version of Entity Framework since code first was released in EF 4.1.

comments powered by Disqus