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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DocumentMap : EntityTypeConfiguration | |
{ | |
public DocumentMap() | |
{ | |
// Primary Key | |
HasKey(t => t.Id); | |
Property(t => t.Number) | |
.IsRequired(); | |
Property(t => t.Indicator) | |
.IsRequired(); | |
Property(t => t.CreatedDate) | |
.IsRequired(); | |
// Table & Column Mappings | |
ToTable("Acc_Documents"); | |
Property(t => t.Id).HasColumnName("Id"); | |
} | |
} |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DocumentDetailMap : EntityTypeConfiguration | |
{ | |
public DocumentDetailMap() | |
{ | |
// other properties mapped | |
// .... | |
// One-Many | |
HasRequired(bd => bd.Document) | |
.WithMany(d => d.DocumentDetails) | |
.HasForeignKey(fk => fk.DocumentId) | |
.WillCascadeOnDelete(); | |
} | |
} |
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