码迷,mamicode.com
首页 > 其他好文 > 详细

EF Code-First 学习之旅 EntityTypeConfiguration<TEntity>

时间:2017-03-30 00:21:21      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:move   实体   man   配置   datetime   ase   span   code   .property   

之前我们配置的实体都都在OnModelCreating方法中,如果有很多实体的话,OnModelCreating方法管理很麻烦

我们可以用单独的类来管理配置,继承EntityTypeConfiguration<TEntity>类实现

public class StudentEntityConfiguration: EntityTypeConfiguration<Student>
{
    public StudentEntityConfiguration()
    {
        
            this.ToTable("StudentInfo");
                
            this.HasKey<int>(s => s.StudentKey);
                
                
            this.Property(p => p.DateOfBirth)
                    .HasColumnName("DoB")
                    .HasColumnOrder(3)
                    .HasColumnType("datetime2");

            this.Property(p => p.StudentName)
                    .HasMaxLength(50);
                        
            this.Property(p => p.StudentName)
                    .IsConcurrencyToken();
                
            this.HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentId");
                            cs.MapRightKey("CourseId");
                            cs.ToTable("StudentCourse");
                        });
    }
}
     

 

 

public class SchoolDBContext: DbContext 
{
    public SchoolDBContext(): base() 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
    public DbSet<StudentAddress> StudentAddress { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            // Moved all Student related configuration to StudentEntityConfiguration class
            modelBuilder.Configurations.Add(new StudentEntityConfiguration());
               
    }
}
        

 

EF Code-First 学习之旅 EntityTypeConfiguration<TEntity>

标签:move   实体   man   配置   datetime   ase   span   code   .property   

原文地址:http://www.cnblogs.com/lanpingwang/p/6642396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!