【CodeFirst Tutorial】 约定(CodeFirst Conventions)

查看原文

命名空间:System.Data.Entity.ModelConfiguration.Conventions 

一、类型发现(Type Discovery)

1、Code-First包含作为DbSet属性在context 类中被定义的类型。

2、Code-First包含实体类型中的引用类型,即使他们是被定义在不同的集合中。

3、Code-First包含继承类,即使只有其基础类被定义在DbSet属性中。

二、主键约定(Primary Key Convention)

如果属性名是 Id 或者<ClassName>Id (不区分大小写), Code-First会自动为其创建主键。主键的数据类型可以是任何类型,但如果主键类型是 numeric 或者 GUID,它会被配置为标识列(identity column)。

如果要定义的主键的属性名不是 Id 或者<ClassName>Id ,会报错(ModelValidationException:Standard' has no key defined. Define the key for this EntityType)。

如果想要定义其他属性名为主键,则需要用 DataAnnotations 或者 Fluent API 来配置。

三、关系约定(Relationship Convention)

Code-First 利用导航属性(navigation property)推断两个实体之间的关系。这个导航属性可以是简单引用,也可以是集合类型。例如,我们在学生类中定义年级(Standard )导航属性,在年级类中定义 ICollection<Student> 导航属性,这样 Code-First 就会通过在学生表中插入Standard_StandardId外键,来创建年级和学生DB表之间的一对多关系。

默认创建的关系外键为 <navigation property Name>_<primary key property name of navigation property type> e.g. Standard_StandardId.

 1 public class Student
 2 {
 3     public Student()
 4     { 
 5         
 6     }
 7     public int StudentID { get; set; }
 8     public string StudentName { get; set; }
 9     public DateTime DateOfBirth { get; set; }
10     public byte[]  Photo { get; set; }
11     public decimal Height { get; set; }
12     public float Weight { get; set; }
13         
14     //Navigation property
15     public Standard Standard { get; set; }
16 }
17 
18 public class Standard
19 {
20     public Standard()
21     { 
22         
23     }
24     public int StandardId { get; set; }
25     public string StandardName { get; set; }
26     
27     //Collection navigation property
28     public IList<Student> Students { get; set; }
29    
30 }
View Code

四、外键约定(Foreign key Convention)

如果学生类中包含了在年级类种作为主键的外键StandardId,Code First 会在学生类中生成 StandardId 列,而不是 Standard_StandardId 列。

五、复杂类型约定(Complex type Convention)

Code First 会为既没有键属性、也没通过 DataAnnotation 或者 Fluent API 注册主键的类,生成复杂类型。

六、默认Code-First约定(Default Code-First Conventions)以及数据类型转换

原文地址:https://www.cnblogs.com/ztpark/p/6829400.html