查看原文

命名空间: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

相关文章:

  • 2021-08-13
  • 2022-02-18
  • 2021-05-17
  • 2022-01-09
  • 2022-02-24
  • 2021-11-13
  • 2021-10-07
猜你喜欢
  • 2021-07-24
  • 2021-08-16
  • 2022-01-05
  • 2022-02-02
相关资源
相似解决方案