Wednesday, January 14, 2015

Entity Framework: Code and Database Separate Approach

The use of EF designers is optionalYou can totally design your database and code separately and independently. You are not required to use any EF designers to reap most of the benefits of the Entity Framework. Here are the general steps for  the Code and Database Separate Approach.
    1. Database: Create and optimize your database as you would normally.
    2. .NET: Create POCO classes (not interfaces) that correspond to database objects. Foreign key references become collections of referenced objects in the POCO instance.
    3. Create a DBContext derived class. Add DBSet<POCO_EntityType> members to DBContext for each DB table/view.
    4. Use methods of DBContext to hydrate DBSets and perform LINQ queries (rich, intuitive, composable, and type safe; paging is supported via Skip and Take) against the DBSets. EF generates and executes appropriate SQL against the database.
    5. You can provide hints to EF, if the default (convention-based) mapping of POCOs to DB objects used by EF is not what you expect. This can be done via attributes (data annotations) or via code.
    6. If you modify the database, simply make corresponding changes to your POCO classes.

Quick Start

If you already have a database and want to create POCO classes from the database, use the Entity Framework Power Tools. Once POCO classes are created fix up the namespaces, move the classes to appropriate project, and make future changes manually, in a controlled fashion.