Entity Framework 表拆分
把一个表拆分成多实体。。例如:把一个博客Blogs表,拆分成Blog、BlogDetail两个实体。
(1)实体类
1 // Blog 2 public class Blog 3 { 4 public int Id { get; set; } 5 6 public string Title { get; set; } 7 8 public string Author { get; set; } 9 10 public DateTime CreatedTime { get; set; } 11 12 public virtual BlogDetail BlogDetail { get; set; } 13 } 14 15 // BlogDetail 16 public class BlogDetail 17 { 18 public int Id { get; set; } 19 20 public string Context { get; set; } 21 22 public virtual Blog Blog { get; set; } 23 }
(2)映射
1 // BlogMap 2 public class BlogMap : EntityTypeConfiguration<Blog> 3 { 4 public BlogMap() 5 { 6 this.ToTable("Blogs"); 7 8 this.HasKey(p => p.Id); 9 10 this.Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 11 this.Property(p => p.Title).IsRequired().HasMaxLength(63); 12 this.Property(p => p.Author).IsRequired().HasMaxLength(31); 13 this.Property(p => p.CreatedTime).IsRequired(); 14 } 15 } 16 17 // BlogDetail 18 public class BlogDetailMap : EntityTypeConfiguration<BlogDetail> 19 { 20 public BlogDetailMap() 21 { 22 this.ToTable("Blogs"); 23 24 this.HasKey(p => p.Id); 25 26 this.Property(p => p.Context).IsOptional(); 27 28 this.HasRequired(p => p.Blog) 29 .WithRequiredPrincipal(p => p.BlogDetail); 30 } 31 } 32 33 // DbContext 34 public class ConsAppContext : DbContext 35 { 36 public IDbSet<Blog> BlogSet { get; set; } 37 38 public IDbSet<BlogDetail> BlogDetaisSet { get; set; } 39 40 protected override void OnModelCreating(DbModelBuilder modelBuilder) 41 { 42 modelBuilder.Configurations.Add(new BlogMap()); 43 modelBuilder.Configurations.Add(new BlogDetailMap()); 44 base.OnModelCreating(modelBuilder); 45 } 46 }
(3)生成效果