Friday, 18 February 2011

O/RM Schema Design Approaches

I've spent this afternoon looking at the various schema design approaches available to an O/RM user, in the context of Entity Framework (EF).
Database First


In this approach, a database is first designed in a "traditional" way. A .edmx file in used within the solution to generate entity classes (very similar to the way LINQ-to-SQL works).


Code First (CTP5 only)


In this approach POCO entity classes are manually created in the solution, and EF deals with all aspects of persistence - it will create the database and all tables for you. If the POCOs are subsequently changed, EF will drop and recreate the database, with any stock data that you specify. This solution is not designed for production environments - only early development stages. The EF team are working on a schema/data migration solution, but this is not in CTF5 and is unlikely to be in the RTM release of EF's next version (due Q1 2011).


"Code First" with Existing Database (CTP5 only)


In this approach a database is first designed in a "traditional" way. POCOs are then manually created in the solution, and EF is made aware of their presence - noting that the schemas match, EF shouldn't make any changes at this point (see scottgu for an in-depth explanation).


---


IMO, the third option givens the most flexibility in the absence of an automated migration solution. If the database is designed first, developers have a better understanding of the schema and should therefore be in a better position to write change scripts against it. Being able to keep POCOs is very nice too.


---


NB a very good article comparing EF 4 with NHibernate 3 can be found here. It's well worth reading all of the parts in the series - there are links to the other parts at the bottom the article.

2 comments:

  1. In the option we are calling "The Third Option", if the schema doesn't match the POCOs (because you haven't run another developers SQL script for instance), what happens? I guess I hope the answer is that an exception is thrown, rather than EF drops and recreates the entire schema...

    ReplyDelete
  2. It's configurable - it can:

    - drop & recreate
    - drop & recreate with stock data
    - throw an exception

    ReplyDelete