EF中关系映射也是一个很关键的内容,关系映射和属性映射同样,也是在 OnModelCreating 中配置映射。EF中的关系映射有以下三种:数据库
咱们今天先讲解 One-to-Many Relationship(一对一关系)ide
public abstract class Base { public int Id { get; set; } public DateTime CreateTime { get; set; } public DateTime ModifiedTime { get; set; } }
public class Customer : Base { public string Name { get; set; } public string Email { get; set; } public virtual ICollection<Order> Orders { get; set; } } public class Order : Base { public byte Quanatity { get; set; } public int Price { get; set; } public int CoustomerId { get; set; } public virtual Customer Customer { get; set; } }
在编写代码以前,咱们先分析一下客户和订单的关系。一个客户能够有多个订单,但一个订单只能属于一个客户,因此咱们用到了EF中的 HasRequired,一个客户又存在多个订单,所以也使用到了 WithMany ,同时 Order 表中有 CustomerId 做为外键,所以咱们用到了 HasForeignKey 。根据咱们的分析,编写代码以下:ui
public class CustomerMap : EntityTypeConfiguration<Customer> { public CustomerMap() { //数据库映射的表名称 ToTable("Customer"); //主键 HasKey(p => p.Id); //属性映射的字段属性 Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50).IsRequired(); Property(p => p.Email).HasColumnType("VARCHAR").HasMaxLength(50).IsRequired(); Property(p => p.CreateTime); Property(p => p.ModifiedTime); //设置关系 HasMany(t => t.Orders).WithRequired(t => t.Customer).HasForeignKey(t => t.CoustomerId).WillCascadeOnDelete(false); } } public class OrderMap : EntityTypeConfiguration<Order> { public OrderMap() { ToTable("Order"); HasKey(p => p.Id); Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(p => p.Quanatity); Property(p => p.Price); Property(p => p.CoustomerId); Property(p => p.CreateTime); Property(p => p.ModifiedTime); } }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { var typeToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach(var type in typeToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } base.OnModelCreating(modelBuilder); }
注1:在实际项目中须要编写不少的实体类,若是将全部实体类的映射直接写在 OnModelCreating 中会形成代码臃肿,不易维护,所以咱们在这里将每一个类的映射写在对应的映射文件中,最后再将每一个类的映射类注册到 OnModelCreating 中注2:上述代码和描述是从客户的方向连编写的关系映射,若是以订单的角度来编写关系映射的话,只需删掉CustomerMap中的关系配置,在OrderMap中增长关系配置部分修改以下:spa
HasRequired(p => p.Customer).WithMany(p => p.Orders).HasForeignKey(p => p.CoustomerId).WillCascadeOnDelete(false);
运行控制台代码后,咱们将在数据库看到表和表关系都被建立了:code