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.

No comments:

Post a Comment