项目学习之OnModelCreating

摘自MSDN:

This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.

在Code First方法中,还可以通过Fluent API的方式来处理实体与数据表之间的映射关系。要使用Fluent API必须在构造自定义的DbContext时,重写OnModelCreating方法,在此方法体内调用Fluent API。

 1  public class OceanSampleDatabase : DbContext, IDatabase
 2  {    

        //配置移除多重级联删除
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

      ////////////////////////////////////////////////////
4 5 protected override void OnModelCreating(DbModelBuilder modelBuilder) 6 { 7      //与StorageBox一对一以及一对多关系处理 8 modelBuilder.Entity<StorageBoxStateHistory>() 9 .HasRequired(s => s.StorageBox) 10 .WithMany(s => s.StorageBoxStateHistorys) 11 .HasForeignKey(s => s.StorageBoxID); 12 modelBuilder.Entity<StorageBoxStateHistory>().ToTable("StorageBoxStateHistory"); 13 modelBuilder.Entity<StorageBoxType>().ToTable("StorageBoxType");
      }
14 }

more details you can find in this article:http://msdn.microsoft.com/en-US/data/jj591620

原文地址:https://www.cnblogs.com/super86/p/3001150.html