体验EF5 Code First(2) 类与数据库表字段的映射处理
在上篇文章(体验EF5 Code First)中只是简要的体验了一把Code First,非常基础,连实体与表字段的映射都没有提及,这篇文章就来简要的体验下实体类与数据库的关联映射。
1、这里新增了两个实体类,MainTables和SubTables.他们的关系是1:*
其中MainTables为
public class MainTable { public MainTable() { this.SubTables = new List<SubTable>(); } public string ID { get; set; } public string Name { get; set; } public virtual ICollection<SubTable> SubTables { get; set; } }
SubTables为
1 public class SubTable 2 { 3 public string Id { get; set; } 4 public string MainId { get; set; } 5 public string SubName { get; set; } 6 public virtual MainTable MainTable { get; set; } 7 }
建立好实体类后,我们需要建立映射关系类MainTableMap和SubTableMap。
其中MainTableMap
1 public class MainTableMap : EntityTypeConfiguration<MainTable> 2 { 3 public MainTableMap() 4 { 5 // Primary Key 6 this.HasKey(t => t.ID); 7 8 // Properties 9 this.Property(t => t.ID) 10 .IsRequired() 11 .HasMaxLength(50); 12 13 this.Property(t => t.Name) 14 .HasMaxLength(50); 15 16 // Table & Column Mappings 17 this.ToTable("MainTable"); 18 this.Property(t => t.ID).HasColumnName("Id"); 19 this.Property(t => t.Name).HasColumnName("Name"); 20 } 21 }
SubTableMap
1 public SubTableMap() 2 { 3 // Primary Key 4 this.HasKey(t => t.Id); 5 6 // Properties 7 this.Property(t => t.Id) 8 .IsRequired() 9 .HasMaxLength(50); 10 11 this.Property(t => t.MainId) 12 .HasMaxLength(50); 13 14 this.Property(t => t.SubName) 15 .HasMaxLength(50); 16 17 // Table & Column Mappings 18 this.ToTable("SubTable"); 19 this.Property(t => t.Id).HasColumnName("Id"); 20 this.Property(t => t.MainId).HasColumnName("MainId"); 21 this.Property(t => t.SubName).HasColumnName("SubName"); 22 23 // Relationships 24 this.HasOptional(t => t.MainTable) 25 .WithMany(t => t.SubTables) 26 .HasForeignKey(d => d.MainId); 27 28 } 29 }
建立了映射关系后,只需修改下在DbContext的实现类中重载OnModelCreating方法,把映射加上Configurations。
1 public class DataTestContext : DbContext 2 { 3 static DataTestContext() 4 { 5 Database.SetInitializer<DataTestContext>(null); 6 } 7 8 public DataTestContext() 9 : base("Name=DataTestContext") 10 { 11 } 12 13 public DbSet<MainTable> MainTables { get; set; } 14 public DbSet<SubTable> SubTables { get; set; } 15 16 17 protected override void OnModelCreating(DbModelBuilder modelBuilder) 18 { 19 modelBuilder.Configurations.Add(new MainTableMap()); 20 modelBuilder.Configurations.Add(new SubTableMap()); 21 22 } 23 }
OK,收工!