本篇随笔目录:

  1、外键列名默认约定

  2、一对多关系

  3、一对一关系

  4、多对多关系

  5、一对多自反关系

  6、多对多自反关系

  在关系数据库中,不同表之间往往不是全部都单独存在,而是相互存在关联的。两个不同表之间可以存在外键依赖关系,一个表自身也可以有自反关系(表中的一个字段引用主键,从而也是外键字段)。

  Entity Framework Code First默认多重关系的一些约定规则:

  一对多关系:两个类中分别包含一个引用和一个集合属性,也可以是一个类包含另一个类的引用属性,或一个类包含另一个类的集合属性。如在本篇接下来用到的例子Category类和Product类,要使得Category与Product之间具有一对多关系,Entity Framework Code First可以有3种体现方式:

  1>、在Category类中定义ICollection<Product> Products集合属性,同时在Product类中定义Category Category引用属性。

  2>、仅在Category类中定义ICollection<Product> Products集合属性。

  3>、仅在Product类中定义Category Category引用属性。

  多对多关系:两个类分别包含对方的一个集合属性。如在本篇接下来用到的例子User类和Role类,要使得User与Role之间具有多对多关系,即一个用户可以属于多个角色,一个角色可以有多个用户,则需要在User类中需要定义一个ICollection<Role> Roles集合属性,同时在Role类中需要定义一个ICollection<User> Users属性。

  一对一关系:两个类分别包含对方的一个引用属性。如在本篇接下来用到的例子User类和UserProfile类,要使得User与UserProfile之间具有一对一关系,则需要在User类中定义一个UserProfile UserProfile的引用属性,同时在UserProfile类中定义一个User User的引用属性。

  下面具体描述Entity Framework Code First生成外键的默认约定,并通过实例展示Entity Framework Code First处理一个表及多个表之间的关系。

  1、外键列名默认约定

  Entity Framework Code First在根据默认约定创建外键时,外键列的名称存在3种方式。在《Programming Entity Framework Code First》一书中,给出的3种外键列名的约定方式是:[Target Type Key Name], [Target Type Name] + [Target Type Key Name], or [Navigation Property Name] + [Target Type Key Name],对应的中文翻译为:[目标类型的键名],[目标类型名称]+[目标类型键名称],或[引用属性名称]+[目标类型键名称]。

  Entity Framework Code First外键默认约束生成的外键在分别满足3种不同的条件下,外键列名有3种不同的命名规则。且经过测试这3种不同的外键名称命名之间存在优先级:[目标类型的键名] > [引用属性名称]+[目标类型键名称] > [目标类型名称]+[目标类型键名称]。接下来以Product类及Category类为例,分别测试外键列名称的3中不同生成方式,Category与Product为一对多关系。

  1>、[目标类型的键名]

  这种方式为要求在Product表中外键列名与Category表中的主键列名相同,所以也就要求在Product类中有定义与Category类中作为主键的属性。如在Category类中主键属性为CategoryID,则需要在Product类中也定义一个CategoryID的属性。

  文件Category.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Category{public int CategoryID { get; set; }public string CategoryName { get; set; }public virtual ICollection<Product> Products { get; set; }}
}

View Code

  文件Product.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Product{public int ProductID { get; set; }public string ProductName { get; set; }public decimal UnitPrice { get; set; }public int CategoryID { get; set; }public virtual Category Category { get; set; }}
}

View Code

  说明:在Category类及Product类中的引用属性及集合属性前加virtual修饰,为的是Entity Framework Code First的延迟加载功能。不使用virtual修饰,在Category类的一个实例要查询包含的Product实例时,将不会启用延迟加载。当然Entity Framework Code First延迟加载并不是必须的,所以virtual修饰符也可以不加。

  在定义以上两个类之后,不再添加任何的Entity Framework Code First与数据库的映射配置,运行之后,生成的数据表结构为:

  从生成的Categories与Products表结构可以看出,在Products表中的外键CategoryID与引用的表Categories主键名称相同。跟踪Entity Framework Code First生成数据表的执行脚本可以看到具体生成外键的SQL语句。

ALTER TABLE [dbo].[Products] ADD CONSTRAINT [FK_dbo.Products_dbo.Categories_CategoryID] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[Categories] ([CategoryID]) ON DELETE CASCADE

  同时,从生成外键的脚本还能看出一点,Entity Framework Code First生成外键是启用级联删除功能的。即当删除Categories表中一条记录时,数据库会自动联带删除Products表中属于该类别的记录。

  在数据库中生成的Products表,查看外键FK_dbo.Products_dbo.Categories_CategoryID属性,其的确有启用级联删除功能。

  2>、[目标类型名称]+[目标类型键名称]

  这种方式要求在Product表中外键列名为Category类名+Category类中键名称,即在Products表中生成的外键名称为Category_CategoryID。示例:在Category类中添加ICollection<Product> Products的集合属性,而在Product类中不做任何与Category关联的代码,也不定义CategoryID属性。

  文件Category.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Category{public int CategoryID { get; set; }public string CategoryName { get; set; }public virtual ICollection<Product> Products { get; set; }}
}

View Code

  文件Product.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Product{public int ProductID { get; set; }public string ProductName { get; set; }public decimal UnitPrice { get; set; }}
}

View Code

  在定义以上两个类之后,不再添加任何的Entity Framework Code First与数据库的映射配置,运行之后,生成的数据表结构为:

  3>、[引用属性名称]+[目标类型键名称]

  这种方式为要求在Product表中外键列名为在Product类中引用Category的属性名称 + Category类的主键名称。如:在Product类中定义一个Category属性Cat,则生成的外键名称为Cat_CategoryID。

  文件Category.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Category{public int CategoryID { get; set; }public string CategoryName { get; set; }}
}

View Code

  文件Product.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Product{public int ProductID { get; set; }public string ProductName { get; set; }public decimal UnitPrice { get; set; }/// <summary>/// 这里为演示,使用Cat作为Category的缩写。/// </summary>public virtual Category Cat { get; set; }}
}

View Code

  在定义以上两个类之后,不再添加任何的Entity Framework Code First与数据库的映射配置,运行之后,生成的数据表结构为:

  关于3种不同的外键名称命名之间存在优先级:[目标类型的键名] > [引用属性名称]+[目标类型键名称] > [目标类型名称]+[目标类型键名称]的测试方法:

  [目标类型的键名]的最高优先级:只要在Product类中定义了CategoryID的属性,在Products表中生成的外键列名都只会为CategoryID。

  [引用属性名称]+[目标类型键名称] > [目标类型名称]+[目标类型键名称]:只要在Product类中定义Cat属性,不管Category类中是否定义Products属性,生成的Products表中外键都只会是Cat_CategoryID。

  2、一对多关系

  Entity Framework Code First在根据定义的类生成数据表时,数据表之间的外键关系及所生成的外键列名有默认的约定。但这种约定同样可以进行修改,如将不满足默认外键约定的属性来作为生成表的外键。示例:Category类与Product类,在Product类中定义一个属性CatID,要将CatID属性作为Product的引用Category的外键,而按照Entity Framework Code First的默认约定是不会的。要做到需要的CatID作为外键,同样可以使用Data Annotations和Fluent API两种方式实现。

  1>、Data Annotations方式

  文件类Category.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Category{public int CategoryID { get; set; }public string CategoryName { get; set; }public virtual ICollection<Product> Products { get; set; }}
}

View Code

  文件类Product.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.ComponentModel.DataAnnotations.Schema;namespace Portal.Entities
{public class Product{public int ProductID { get; set; }public string ProductName { get; set; }public decimal UnitPrice { get; set; }public int CatID { get; set; }[ForeignKey("CatID")]public virtual Category Category { get; set; }}
}

View Code

  在定义以上两个类之后,不再添加任何的Entity Framework Code First与数据库的映射配置,运行之后,生成的数据表结构为:

  查看Products表的外键咧CatID引用关系:

  其中,在Product类中,为设置CatID属性为外键的代码为:

public int CatID { get; set; }
[ForeignKey("CatID")]
public virtual Category Category { get; set; }

  该段实现方式还可以改为:

[ForeignKey("Category")]
public int CatID { get; set; }
public virtual Category Category { get; set; }

  2>、Fluent API方式

  文件类Category.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Category{public int CategoryID { get; set; }public string CategoryName { get; set; }public virtual ICollection<Product> Products { get; set; }}
}

View Code

  文件类Product.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public class Product{public int ProductID { get; set; }public string ProductName { get; set; }public decimal UnitPrice { get; set; }public int CatID { get; set; }public virtual Category Category { get; set; }}
}

View Code

  文件类PortalContext.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.Data.Entity;using Portal.Entities;namespace Portal
{public class PortalContext : DbContext{static PortalContext(){Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PortalContext>());}public DbSet<Category> Categories { get; set; }public DbSet<Product> Products { get; set; }protected override void OnModelCreating(DbModelBuilder modelBuilder){modelBuilder.Entity<Category>().HasMany(t => t.Products).WithRequired(t => t.Category).HasForeignKey(d => d.CatID);modelBuilder.Entity<Product>().HasRequired(t => t.Category).WithMany(t => t.Products).HasForeignKey(d => d.CatID);}}
}

View Code

  说明:在PortalContext.cs的OnModelCreating方法中,对两个实体类Category及Product均添加了Fluent API形式的关系配置。对于Entity Framework Code First而言,两个实体类之间的关系,可以两个类中均添加关系映射配置,也可以只对其中任意一个实体类添加关系映射配置。即在PortalContext.cs的OnModelCreating方法中可以只包含Category或只包含Product类的关系映射配置。这里从Entity Framework Code First的使用经验及技巧,建议将实体类之间关系映射配置在包含外键的类中。即OnModelCreating中只添加对Product实体类的关系映射配置,这样做有一个好处,当Category有多个表引用它时,可以将外键均配置在引用它的实体类中,从而降低Category类的复杂度,同时也有益于代码的维护。

  即在PortalContext.cs的OnModelCreating方法只需下面的定义即可:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{modelBuilder.Entity<Product>().HasRequired(t => t.Category).WithMany(t => t.Products).HasForeignKey(d => d.CatID);
}

  Entity Framework Code First根据一对多关系关系生成的外键引用约束默认是有级联删除的,可以通过以下方式禁用Category与Product之间的级联删除。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{modelBuilder.Entity<Product>().HasRequired(t => t.Category).WithMany(t => t.Products).HasForeignKey(d => d.CatID).WillCascadeOnDelete(false);
}

  也可以在Entity Framework Code First生成的全部表中都统一设置禁用一对多级联删除。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

  虽然Entity Framework Code First是可以支持外键列名自定义的,但在实际的项目中,更多的外键列名称还是与所引用表的主键列名相同。即在Category表中主键为CategoryID,在Product表中外键列名称还是为CategoryID。

  Entity Framework Code First的Fluent API配置实体类与表的映射关系,还可以将所有的实体类与表的映射全部写在一个类中,这样可以方便代码的维护。

  文件类Category.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Portal.Entities
{public partial class Category{public Category(){this.Products = new List<Product>();}public int CategoryID { get; set; }public string CategoryName { get; set; }public virtual ICollection<Product> Products { get; set; }}
}

View Code

  文件类CategoryMap.cs,用于描述Category类与生成的表之间的映射关系:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class CategoryMap : EntityTypeConfiguration<Category>{public CategoryMap(){// Primary Keythis.HasKey(t => t.CategoryID);// Propertiesthis.Property(t => t.CategoryName).IsRequired().HasMaxLength(50);// Table & Column Mappingsthis.ToTable("Category");this.Property(t => t.CategoryID).HasColumnName("CategoryID");this.Property(t => t.CategoryName).HasColumnName("CategoryName");}}
}

View Code

  文件类Product.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public partial class Product{public int ProductID { get; set; }public int CategoryID { get; set; }public string ProductName { get; set; }public Nullable<decimal> UnitPrice { get; set; }public Nullable<int> Quantity { get; set; }public virtual Category Category { get; set; }}
}

View Code

  文件类ProductMap.cs,用于描述Product类与生成的表之间的映射关系:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class ProductMap : EntityTypeConfiguration<Product>{public ProductMap(){// Primary Keythis.HasKey(t => t.ProductID);// Propertiesthis.Property(t => t.ProductName).IsRequired().HasMaxLength(100);// Table & Column Mappingsthis.ToTable("Product");this.Property(t => t.ProductID).HasColumnName("ProductID");this.Property(t => t.CategoryID).HasColumnName("CategoryID");this.Property(t => t.ProductName).HasColumnName("ProductName");this.Property(t => t.UnitPrice).HasColumnName("UnitPrice");this.Property(t => t.Quantity).HasColumnName("Quantity");// Relationshipsthis.HasRequired(t => t.Category).WithMany(t => t.Products).HasForeignKey(d => d.CategoryID);}}
}

View Code

  PortalContext.cs的OnModelCreating方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{modelBuilder.Configurations.Add(new CategoryMap());modelBuilder.Configurations.Add(new ProductMap());
}

View Code

  3、一对一关系

  在一对一关系中,两个表均有各自的主键,但要看哪个表的主键同时作为外键引用另一个表的主键。示例以User类与UserProfile类作为两个具有一对一关系的类,其中User类包含作为主键的UserID属性,UserProfile类包含作为主键的ProfileID的属性。

  1>、Data Annotations方式

  文件类User.cs:

using System;
using System.Collections.Generic;using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace Portal.Entities
{public partial class User{[Key]public int UserID { get; set; }public string UserName { get; set; }public string Password { get; set; }public Nullable<bool> IsValid { get; set; }public virtual UserProfile UserProfile { get; set; }}
}

View Code

  文件类UserProfile.cs:

using System;
using System.Collections.Generic;using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace Portal.Entities
{public partial class UserProfile{[Key][ForeignKey("User")]public int ProfileID { get; set; }public string Name { get; set; }public Nullable<bool> Sex { get; set; }public Nullable<DateTime> Birthday { get; set; }public string Email { get; set; }public string Telephone { get; set; }public string Mobilephone { get; set; }public string Address { get; set; }public Nullable<DateTime> CreateDate { get; set; }public virtual User User { get; set; }}
}

View Code

  在定义以上两个类之后,不再添加任何的Entity Framework Code First与数据库的映射配置,运行之后,生成的数据表结构为:

  在生成的数据表中,UserProfile表中的主键ProfileID同时也作为外键引用User表中的主键UserID。

  修改文件类User.cs:

using System;
using System.Collections.Generic;using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace Portal.Entities
{public partial class User{[Key][ForeignKey("UserProfile")]public int UserID { get; set; }public string UserName { get; set; }public string Password { get; set; }public Nullable<bool> IsValid { get; set; }public virtual UserProfile UserProfile { get; set; }}
}

View Code

  修改文件类UserProfile.cs:

using System;
using System.Collections.Generic;using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace Portal.Entities
{public partial class UserProfile{[Key]public int ProfileID { get; set; }public string Name { get; set; }public Nullable<bool> Sex { get; set; }public Nullable<DateTime> Birthday { get; set; }public string Email { get; set; }public string Telephone { get; set; }public string Mobilephone { get; set; }public string Address { get; set; }public Nullable<DateTime> CreateDate { get; set; }public virtual User User { get; set; }}
}

View Code

  则实体类执行之后生成的数据表User主键UserID将同时作为外键引用UserProfile表的主键ProfileID。

  2>、Fluent API方式

  Fluent API设置实体类生成的表引用与被引用通过WithRequiredPrincipal、WithRequiredDependent及WithOptionalPrincipal、WithOptionalDependent来设置,使用Principal属性的实体类将被另外的实体类生成的表引用,使用Dependent属性的实体类将引用另外的实体类。

  文件类User.cs:

using System;
using System.Collections.Generic;using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace Portal.Entities
{public partial class User{public int UserID { get; set; }public string UserName { get; set; }public string Password { get; set; }public Nullable<bool> IsValid { get; set; }public virtual UserProfile UserProfile { get; set; }}
}

View Code

  映射文件类UserMap.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class UserMap : EntityTypeConfiguration<User>{public UserMap(){// Primary Keythis.HasKey(t => t.UserID);// Propertiesthis.Property(t => t.UserName).HasMaxLength(50);this.Property(t => t.Password).HasMaxLength(100);// Table & Column Mappingsthis.ToTable("User");this.Property(t => t.UserID).HasColumnName("UserID");this.Property(t => t.UserName).HasColumnName("UserName");this.Property(t => t.Password).HasColumnName("Password");this.Property(t => t.IsValid).HasColumnName("IsValid");}}
}

View Code

  文件类UserProfile.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public partial class UserProfile{public int UserID { get; set; }public string Name { get; set; }public Nullable<bool> Sex { get; set; }public Nullable<DateTime> Birthday { get; set; }public string Email { get; set; }public string Telephone { get; set; }public string Mobilephone { get; set; }public string Address { get; set; }public Nullable<DateTime> CreateDate { get; set; }public virtual User User { get; set; }}
}

View Code

  映射文件类UserProfileMap.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class UserProfileMap : EntityTypeConfiguration<UserProfile>{public UserProfileMap(){// Primary Keythis.HasKey(t => t.UserID);// Propertiesthis.Property(t => t.UserID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);this.Property(t => t.Name).IsRequired().HasMaxLength(50);this.Property(t => t.Email).IsRequired().HasMaxLength(100);this.Property(t => t.Telephone).HasMaxLength(50);this.Property(t => t.Mobilephone).HasMaxLength(20);this.Property(t => t.Address).HasMaxLength(200);// Table & Column Mappingsthis.ToTable("UserProfile");this.Property(t => t.UserID).HasColumnName("UserID");this.Property(t => t.Name).HasColumnName("Name");this.Property(t => t.Sex).HasColumnName("Sex");this.Property(t => t.Birthday).HasColumnName("Birthday");this.Property(t => t.Email).HasColumnName("Email");this.Property(t => t.Telephone).HasColumnName("Telephone");this.Property(t => t.Mobilephone).HasColumnName("Mobilephone");this.Property(t => t.Address).HasColumnName("Address");this.Property(t => t.CreateDate).HasColumnName("CreateDate");// Relationshipsthis.HasRequired(t => t.User).WithRequiredDependent(t => t.UserProfile);}}
}

View Code

  在以上实体类及实体映射类执行以后,生成的数据表结构如下:

  在生成的表结构中,UserProfile表中的主键UserID同时也作为外键引用User表的主键UserID。若修改UserProfileMap.cs如下,则生成的表结构User表的主键UserID将作为你外键引用UserProfile表的主键UserID。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class UserProfileMap : EntityTypeConfiguration<UserProfile>{public UserProfileMap(){// Primary Keythis.HasKey(t => t.UserID);// Propertiesthis.Property(t => t.UserID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);this.Property(t => t.Name).IsRequired().HasMaxLength(50);this.Property(t => t.Email).IsRequired().HasMaxLength(100);this.Property(t => t.Telephone).HasMaxLength(50);this.Property(t => t.Mobilephone).HasMaxLength(20);this.Property(t => t.Address).HasMaxLength(200);// Table & Column Mappingsthis.ToTable("UserProfile");this.Property(t => t.UserID).HasColumnName("UserID");this.Property(t => t.Name).HasColumnName("Name");this.Property(t => t.Sex).HasColumnName("Sex");this.Property(t => t.Birthday).HasColumnName("Birthday");this.Property(t => t.Email).HasColumnName("Email");this.Property(t => t.Telephone).HasColumnName("Telephone");this.Property(t => t.Mobilephone).HasColumnName("Mobilephone");this.Property(t => t.Address).HasColumnName("Address");this.Property(t => t.CreateDate).HasColumnName("CreateDate");// Relationshipsthis.HasRequired(t => t.User).WithRequiredPrincipal(t => t.UserProfile);}}
}

View Code

  4、多对多关系

  Entity Framework Code First在根据定义的多对多关系的类生成数据表时,除了生成实体类定义的属性表之外,还会生成一个中间表。用于体现两个实体表之间的多对多的关系。示例实体类User与Role为多对多关系,一个用户可以属于多个角色,一个角色可以包含多个用户。

  文件类User.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public partial class User{public int UserID { get; set; }public string UserName { get; set; }public string Password { get; set; }public Nullable<bool> IsValid { get; set; }public virtual ICollection<Role> Roles { get; set; }}
}

View Code

  文件类Role.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public partial class Role{public Role(){this.Users = new List<User>();}public int RoleID { get; set; }public string RoleName { get; set; }public virtual ICollection<User> Users { get; set; }}
}

View Code

  在定义以上两个类之后,不再添加任何的Entity Framework Code First与数据库的映射配置,运行之后,生成的数据表结构为:

  从以上的表结构中,可以看出,实体类运行之后,除了生成Users表和Roles表之外,还生成了RoleUsers表作为中介表,体现Users表和Roles表之间的多对多关联关系。中介表RoleUsers的字段生成规则按照 [目标类型名称]+[目标类型键名称] 的约定。

  Entity Framework Code First根据默认约定生成的多对多关联关系的表时,默认启用多对多的数据级联删除,可以添加代码进行禁用。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{// 禁用多对多关系表的级联删除modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}

  FluentAPI实现方式:

  文件类User.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public partial class User{public int UserID { get; set; }public string UserName { get; set; }public string Password { get; set; }public Nullable<bool> IsValid { get; set; }public virtual ICollection<Role> Roles { get; set; }}
}

View Code

  映射文件类UserMap.cs:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class UserMap : EntityTypeConfiguration<User>{public UserMap(){// Primary Keythis.HasKey(t => t.UserID);// Propertiesthis.Property(t => t.UserName).HasMaxLength(50);this.Property(t => t.Password).HasMaxLength(100);// Table & Column Mappingsthis.ToTable("User");this.Property(t => t.UserID).HasColumnName("UserID");this.Property(t => t.UserName).HasColumnName("UserName");this.Property(t => t.Password).HasColumnName("Password");this.Property(t => t.IsValid).HasColumnName("IsValid");}}
}

View Code

  文件类Role.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public partial class Role{public int RoleID { get; set; }public string RoleName { get; set; }public virtual ICollection<User> Users { get; set; }}
}

View Code

  映射文件类RoleMap.cs:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class RoleMap : EntityTypeConfiguration<Role>{public RoleMap(){// Primary Keythis.HasKey(t => t.RoleID);// Propertiesthis.Property(t => t.RoleName).HasMaxLength(50);// Table & Column Mappingsthis.ToTable("Role");this.Property(t => t.RoleID).HasColumnName("RoleID");this.Property(t => t.RoleName).HasColumnName("RoleName");// Relationshipsthis.HasMany(t => t.Users).WithMany(t => t.Roles).Map(m =>{m.ToTable("UserRole");m.MapLeftKey("RoleID");m.MapRightKey("UserID");});}}
}

View Code

  运行之后生成的表结构:

  5、一对多自反关系

  一对多自反关系,即一个表存在一个外键列引用自身的主键。在项目中,最常见的一对多自反关系为分类表,分类表通过一个ParentID列保存引用主键,已实现无限级递归。

  Fluent API实现方式:

  文件类Category.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{public class Category{public int CategoryID { get; set; }public int CategoryNo { get; set; }public string CategoryName { get; set; }public Nullable<int> ParentID { get; set; }public virtual Category Parent { get; set; }public virtual ICollection<Category> Children { get; set; }}
}

View Code

  映射文件类CategoryMap.cs:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class CategoryMap : EntityTypeConfiguration<Category>{public CategoryMap(){// Primary Keythis.HasKey(t => t.CategoryID);// Propertiesthis.Property(t => t.CategoryName).IsRequired().HasMaxLength(50);// Table & Column Mappingsthis.ToTable("Category");this.Property(t => t.CategoryID).HasColumnName("CategoryID");this.Property(t => t.CategoryNo).HasColumnName("CategoryNo");this.Property(t => t.CategoryName).HasColumnName("CategoryName");this.Property(t => t.ParentID).HasColumnName("ParentID");// Relationshipsthis.HasOptional(t => t.Parent).WithMany(t => t.Children).HasForeignKey(d => d.ParentID);}}
}

View Code

  以上代码在运行之后,生成的数据表:

  6、多对多自反关系

  多对多关系示例:Family中一条记录可能有多个Parents,也可能有多个Children。

  文件类Family.cs:

using System;
using System.Collections.Generic;namespace Portal.Entities
{/// <summary>/// Family表多对多自反关系/// </summary>public partial class Family{public Family(){this.Parents = new List<Family>();this.Children = new List<Family>();}public int FamilyID { get; set; }public string Name { get; set; }public Nullable<bool> Sex { get; set; }public Nullable<System.DateTime> Birthday { get; set; }public virtual ICollection<Family> Parents { get; set; }public virtual ICollection<Family> Children { get; set; }}
}

View Code

  映射文件类FamilyMap.cs:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;using Portal.Entities;namespace Portal.Mapping
{public class FamilyMap : EntityTypeConfiguration<Family>{public FamilyMap(){// Primary Keythis.HasKey(t => t.FamilyID);// Propertiesthis.Property(t => t.Name).HasMaxLength(50);// Table & Column Mappingsthis.ToTable("Family");this.Property(t => t.FamilyID).HasColumnName("FamilyID");this.Property(t => t.Name).HasColumnName("Name");this.Property(t => t.Sex).HasColumnName("Sex");this.Property(t => t.Birthday).HasColumnName("Birthday");// Relationshipsthis.HasMany(t => t.Parents).WithMany(t => t.Children).Map(m =>{m.ToTable("FamilyRelationship");m.MapLeftKey("ParentID");m.MapRightKey("ChildID");});}}
}

View Code

  Family类及映射配置类,在运行之后生成的数据表结构:

  在上面的表结构中,指定Family之间的中介表为FamilyRelationship,其中FamilyRelationship的两个字段ParentID及ChildID均引用Familyi表中的FamilyID作为外键。可能在实际的项目过程中,出现这种多对多自反引用关系的情况比较少见。

Entity Framework Code First关系映射约定相关推荐

  1. Entity Framework 一对多关系映射

    EF中关系映射也是一个很关键的内容,关系映射和属性映射一样,也是在 OnModelCreating 中配置映射.EF中的关系映射有如下三种: One-to-Many Relationship(一对多) ...

  2. ADO.NET Entity Framework -Code Fisrt 开篇(一)

    ADO.NET Entity Framework 是微软的一套实体映射框架.发布EF4.1(Entity Framework )时,又提出了代码先行的设计理念(the code comes first ...

  3. Entity Framework Code First添加修改及删除单独实体

    对于一个单独实体的通常操作有3种:添加新的实体.修改实体以及删除实体. 1.添加新的实体 Entity Framework Code First添加新的实体通过调用DbSet.Add()方法来实现. ...

  4. Entity Framework Code First在Oracle下的伪实现

    为什么要说是伪实现,因为还做不到类似MsSql中那样完全的功能.Oralce中的数据库还是要我们自己手动去创建的.这里,我们舍掉了Model First中的EDMX文件,自己在代码里面写模型与映射关系 ...

  5. Entity Framework Code First使用者的福音 --- EF Power Tool使用记之一

    好像蛮长时间没有新文章带给大家了.前几天出差再加上忙着公司里的活儿,几乎都没时间上博客园了.今天正好有些时间,为大家简单介绍EF产品组新发布的一个牛逼的小工具--EF Power Tool(翻译的话, ...

  6. linq、lambda、entity framework之间的关系

    lambda: 一种匿名委托的精简版写法,明显的标志是=>符号 entity framework(简称EF): 微软访问数据库的最快捷最成熟的框架(ORM),在EF出现以前有SqlHelper. ...

  7. 使用Entity Framework code first, migration

    当我使用 entity framework 代码先行的使用, 有时候需要添加字段,为了同步数据库的结构,这时候需要数据库迁移,其实很简单, run 几个命令即可 找到 package manager ...

  8. Entity Framework 5.0系列之约定配置

    Code First之所以能够让开发人员以一种更加高效.灵活的方式进行数据操作有一个重要的原因在于它的约定配置.现在软件开发越来复杂,大家也都试图将软件设计的越来越灵活,很多内容我们都希望是可配置的, ...

  9. ADO.NET Entity Framework -Code Fisrt (二)

    Code First 可以自动根据Model 映射来创建数据库,这点非常方便. 但是按照上一节的方式创建的表,会发现,所有字符串列都是nvarchar(max),就是说每个model的属性映射的表列都 ...

最新文章

  1. 意念实时转语音!Facebook的非植入式脑机接口,解码准确率达到76%
  2. RGBD-SLAM 深度摄像机资料介绍
  3. Android模拟器Genymotion使用详解
  4. Service Mesh 是新瓶装旧酒吗?
  5. c语言用递归法判断回文字符串,递归方式判断一个字符串是否为回文字符串
  6. Pytest标记用例失败之xfail
  7. 看完这篇你就知道什么是无服务器架构了
  8. Leetcode算法题(C语言)11--有效的数独
  9. HTML中段落标签和换行标签分别是,HTML 基本标签
  10. Webstorm配置svn【window系统】
  11. c 语言编程字谜,字谜游戏(a)C语言
  12. 苹果 M1“痛失”Windows 11!
  13. windows启动修复_如何使用Windows启动修复工具修复启动问题
  14. w乐ndows update更新失败,黑鲨教你解决Windows系统update更新失败问题
  15. 【BZOJ1226/SDOI2009】学校食堂Dining
  16. 观察者模式(结合C#,Unity)
  17. arcengin交互式动图制作
  18. 在 JavaScript 中为任何表格添加分页
  19. 我们都是中本聪:那些孜孜以求建立密码学货币的先驱们
  20. C/C++ 栈的应用:表达式求值

热门文章

  1. c# asp.net Pdf 转换图片 在线预览 发布到iis中问题 最终解决篇—_—!
  2. 大地震前有三个明显征兆:1.井水异常2.牲畜反应异常3.专家出来辟谣。但是细心网友指出,第三和第二重复了。...
  3. C# 读取Excel中的时间
  4. JBoss5.1.0部署SSH2
  5. POJ1698 最大流或者匈牙利
  6. hdu4940 有上下界的无源可行流判断
  7. 【Linux 内核 内存管理】优化内存屏障 ④ ( 处理器内存屏障 | 八种处理器内存屏障 | 通用内存屏障 | 写内存屏障 | 读内存屏障 | 数据依赖屏障 | 强制性内存屏障 |SMP内存屏障 )
  8. 【Android WebSocket】Android 端 WebSocket 基本用法 ( 下载 Java-WebSocket源码 | 导入 Java-WebSocket-1.5.2 工程作为依赖 )
  9. 【计算理论】可判定性 ( 对角线方法 | 证明自然数集 N 与实数集 R 不存在一一对应关系 )
  10. [Spring cloud 一步步实现广告系统] 10. 使用Ribbon 实现微服务调用