Share via


When is Code First not code first?

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Code First to a New Database see https://msdn.com/data/jj193542

For Code First to an Existing Database see https://msdn.com/data/jj200620


 

We recently announced the upcoming release of EF 4.1 which includes support for the Code First approach to EF development. This name fits nicely into the three approaches supported by the Entity Framework: Database First, Model First, and Code First. However, it can be a little misleading in that using Code First does not always mean writing your code first.

Database First

The idea behind Database First is that you start with an existing database and use tools (such as the EF Designer in Visual Studio) to generate C# or VB classes from the database. You can modify the classes that are created and the mappings between the classes and the database through the EF designer, or even, if you are feeling brave, through modification of the underlying XML. The key to this approach is that the database comes first and the code and model come later.

Model First

The idea behind Model First is that you start with a blank canvas and then design an Entity Data Model, again using the EF Designer. This model can then be used to generate a database and also to generate C# or VB classes. The key to this approach is that the model comes first and the code and database come later.

Code First generating a database

In the original prototypes of Code First it was actually called Code Only. This was because the only thing that you needed to write was code—the model and the database were created for you. This is the approach we have demoed at conferences and have shown in walkthroughs, etc.

This approach can also be considered a model first approach depending on how you think about your model. The Model First approach described above is for people who like to create an Entity Data Model using a visual designer. However, many developers instead choose to model their application domain using just the code. This approach is often associated with Domain Driven Design (DDD) where the domain model is represented by the code. So, depending on how you view modeling and how you want to represent your model, you may also consider Code First to be a model first approach.

Having Code First generate your database for you is certainly a very powerful approach and we see a lot of people using it, but if it doesn’t work for you then read on!

Code First with an existing database

Imagine you have an existing database and maybe your DBA doesn’t even let you modify that database. Can you still use Code First? The answer is “Yes!” and we are seeing lots of people doing this. Furthermore, this isn’t just an afterthought; Code First has been specifically designed to support this.  The steps are very simple:

  • Make sure your DbContext knows how to find your existing database. One way to do this is to put a connection string in your config file and then tell DbContext about it by passing “name=MyConnectionStringName” to the DbContext constructor. See this post for more details.
  • Create the classes that you want to map to your database.
  • Add additional mapping using data annotations or the Code First fluent API to take care of the places where the Code First conventions need to be overridden to get correct mappings.

This approach is essentially a database first approach, but using code for the mapping instead of a visual designer and XML. We hope to make a T4 template available that would start from an existing database and do the above steps for you—we’d like to hear from you if you would find such a template useful.

Code First != DbContext

The first time most people see DbContext is when using Code First. However, DbContext can also be used together with an EDMX file for traditional Database First and  Model First development. The T4 templates that shipped with CTP5 and that will ship as part of EF 4.1 create a context class derived from DbContext. This is not a Code First context and it will not build a model from data annotations or fluent API calls. Instead it loads the EDMX file at runtime (just like ObjectContext does) and uses the mappings defined in that file. This gives you the improved API surface of DbContext while maintaining the Database First or Model First approach.

It is also possible to use Code First to create an ObjectContext instead of a DbContext. However, we generally don’t recommend that you use this approach.

So is Code First right for me?

The bottom line on whether Code First is right for you depends on how you like to create and store your C#/VB classes and the mapping between those classes and the database. If you like to use code for this, then Code First is probably for you. This is true even if you don’t want the code to create the database, possibly because it already exists and/or is locked down by your DBA.

If you prefer a visual designer and XML files, then Database First or Model First is probably better for you.

As always we would love to hear any feedback you have by commenting on this blog post.

For support please use the Entity Framework Pre-Release Forum.

Arthur Vickers
Developer
ADO.NET Entity Framework

Comments

  • Anonymous
    March 08, 2011
    Is there any performance differences between the approaches?

  • Anonymous
    March 08, 2011
    T4 Template = yes please!

  • Anonymous
    March 08, 2011
    Yes!! I would love a T4 template that creates Code "First" mappings from an existing database...!

  • Anonymous
    March 09, 2011
    Yes! A Template for Code First from a Existing database will be great!

  • Anonymous
    March 09, 2011
    We desperately need Table-View-Function support with EF together with Code First. Is there a workaround that we can do so that I can have composed queries using TVFs executed on the server like it can be done with Linq2Sql?  Worst case how can we get TVFs to work in POCO and Edmx?

  • Anonymous
    March 10, 2011
    Have tried to implement Entity Framework in projects before, but don't feel comfortable using the visual designer. Now with the new EF Code First that gives me full control I can finally use it in our new projects. Would also like to see a T4 template.

  • Anonymous
    March 10, 2011
    @Drew The main point in time when you'll see a performance difference between using an edmx file for a model and using Code First to build your model is during the first instantiaition of your DbContext. With Code First, this is when the code is run to build out the equivalent of the edmx file in memory and this is something that you do not have to do with an edmx file since the model is already pre-defined. However, on repeated instantiations of a DbContext, everything is cached in both cases so there isn't a signficant performance difference.

  • Anonymous
    March 10, 2011
    Glad to see there is interest on the T4 template. We'll see what we can do about adding this to the extension manager.

  • Anonymous
    March 10, 2011
    @Orlin Table-value function is support is something we are working on adding to the Entity Framework, and while it will not be part of the upcoming Entity Framework 4.1 release, we are currently targetting the release following that one. We hope to get a CTP of that functionality out mid-this year.

  • Anonymous
    March 14, 2011
    When is Model First not Model First? I have to work with an existing database, but I want to design a clean entity model for my application and then map my database onto that model. But the Entity Framework doesn't support that process, despite the fact that all of the tools needed to do it exist, they just haven't been wired up. Am I really the only person who wants to use such functionality?

  • Anonymous
    April 21, 2011
    T4 template for both data annotations and fluent api would be cool.

  • Anonymous
    May 03, 2011
    A T4 Template with INotifyPropertyChanged is definately needed. The DbContect actually has these nice "Local" ObservableCollections on each DbSet, ready to use in WPF DataBinding, but the POCOs generated by the current template do not play nice with WPF.. Perhaps you could deliver two sets of templates, one for simple POCOs and one for observable POCOs in future, selectable on Add Code Generation dialog?

  • Anonymous
    June 14, 2012
    I design both database and code-first conceptual model manually, but need a tool which can compare my db schematic with code-first model and show the differences or incompatibility issues if any.

  • Anonymous
    June 20, 2012
    @Konstantin Tarkus – I assume you are targeting the same database with both models? Probably the easiest way is to temporarily point the Code First model at a different database (that doesn’t exist) and let it create the schema… and then use a schema compare tool (some SKUs of Visual Studio include one under the Data menu in VS 2010 and SQL menu in VS 2012). Just in case you didn’t see it, we also have Power Tools that can reverse engineer a Code First model from an existing database - blogs.msdn.com/.../ef-power-tools-beta-2-available.aspx.

  • Anonymous
    August 01, 2012
    T4 template very very usefull Pelase!

  • Anonymous
    August 13, 2014
    I use code first in my program, when it is runing , the model needs to change the table it maps becouse the table stores too much data.  i overwrite onmoedlcreating function, but it only run one time when the program starts, so what shuould i do .

  • Anonymous
    August 13, 2014
    @anan: you would need OnModelCreating to be called once for each distinct table you need to map your entity to. You can achieve that by overriding the default mechanism EF uses to calculate the cache key for the model so that it will take into account the variable table name. There are currently two different ways to override the service: (a) implement the IDbModelCacheKeyProvider interface on your context and (b) provide a cache key factory to the  SetModelCachKey method on a derived DbConfiguration. The following thread in StackOverflow provides an example of the first approach (note that in the example what varies is the schema name and not a table name): stackoverflow.com/.../multi-tenant-with-code-first-ef6.

  • Anonymous
    August 13, 2014
    thank you very much and i will have a try.