Friday, June 24, 2011

EF Code-First in the shape of NHibernate - Using (5/5)



Once your database is built, using EF Code-First for the rest of the project is as easy as NHibenate. Same Patterns like Repository, Unit of work... can be applied to the codes in your application.

Even there is no difference between Code-First or Database-First (the one that you create your model out of your database) mode in your business logic code.

By this approach your model (Genrally POCO [ Plain Old CLR Object]) is first initialized and database is built as the result of your object model. By some tricks like migrations you can narrow your database recreation down to some field name modification or changes in size.

EF Code-First in the shape of NHibernate - Migrating Changes (4/5)

One of the hassles every application developer might have faced during his/her career is how to best synchronize changes between model and database schemas (versioning problem).Several solutions have been proposed but I personally believe ORM tools should care about this problem in their hearts.

Microsoft's EntityFramework.Migrations is a tool designed for going over such hurdles. Although it has some incompatibilities between different versions of EF, but it looks promising. Technically speaking, the tool checks current object model with the one on database( if any). Any differences are detected and written to a script file and finally migration tool is in charge of running the script file and applies changes to database. 

Note : All you have to do to install is write Install-Package  EntityFramework.Migrations in package manager console.  

There 2 ways to create migration, Manual Migration that uses code-based migration and Automatic. I will pick automatic which is very easy to use.
All we have to write is :

    public class Settings : DbMigrationContext<YourContext>
    {
        public Settings()
        {
            AutomaticMigrationsEnabled = true;
            SetCodeGenerator();
            AddSqlGenerator();
        }
    }

Note: replace YourContext with your DbContext class in your project.


Two commands are handy in migration panel.

  • Add-Migration name that generates a script file for all the changes between object model and database schema.  
  • Update-Migration that pushes all pending changes to the database and applies them on database.

Friday, June 10, 2011

EF Code-First in the shape of NHibernate - Mapping Files (3/5)

Once the DbContext is configured, Let's take a look at how can EF comprehend our model and generates schema out of it.

Simply EF looks through all classes listed in OnModelCreating() method, and based on some conventions, it realizes that which classes has to be converted into SQL tables, their SQL column attributes(name, type, size..) and how they are associated with each other. i.e One to One, One to Many, Many to Many.

For those NHibenate users who are pretty familiar with FluentNHibernate.Org, that is really easy for them to switch to EF conventions.

Here's the what DocumentMap looks like:


As you see all mapping classes should inherit from EntityTypeConfiguration. This class accepts a generic class and it has to be our domain class.
By looking at the class internals, you' ll see some conventions are used :
   1. HasKey gets primary key for the table as lambda expression.
  2. Property gets Number property in Document model as SQL column and set as not null.
  3. ToTable sets the name of generated table.

All other properties are converted to SQL columns based on EF conventions.( Note; the EF conventions can be modified manually but that's beyond the purpose of this series)

Same thing applies to DoumentDetailMap, but there is a little tricky point in setting up One-Many in mapping class.




as it clearly shows, HasRequired get Document object in DocumentDetails class then it calls WithMany that related Document to DocumentDetails. Foreign keys can be included in config and at the end, relation can be set to delete all children orphaned rows.

Friday, June 3, 2011

EF Code-First in the shape of NHibernate - Data Context (2/5)


Context in EF are the same as Sessions in Nhibernate. It's very expensive to create and once it's been created we have to watch it till it's been disposed.


Context in EF can be configured simply by inherit from DbContext(System.Data.Entity). You can also inject your ConnectionString  into the context before it's been constructed. Once any ConnectionString mentioned, EF gets its configuration from local SQLExpress on your machine. 


There is only one method that should be overridden when using this approach, OnModelCreating. This method is responsible to go through all mapping classes (next post on the series) and create schema that a database engine needs.




On the next post, I am going through the details of DocumentMap, DocumentDetailMap.

FA |-| I M

EF Code-First in the shape of NHibernate (1/5)

When I have first come across Entity Framework, I was looking for the ways to put my database schema generated by the object model I have in my domain model. This way, I feel like I am coding in NHibenate that makes me satisfied with the result. Because of the testability, maintainability it brings to my code.Unfortunately, It was practically impossible to code that way till now that Microsoft released Entity Framework 4.1 Code-First. 
In the following series I am going to show some of the ways that might be helpful for production code that are very much close to the NHibernate's best practices but this time EF is under the hood. 
My domain model is simple accounting model used for my pet project.





Before I go further, Latest versions of Entity Framework(including code-first) can be get via nuget.org.
You can write (Install-Package EntityFramework) in package manager and get the entity framework.