EntityFramework - Code First - 关系
Student
public class Student { public int ID { get; set; } public string Name { get; set; } }
Teacher
public class Teacher { public int ID { get; set; } public string Name { get; set; } }
注意: 一对多关系下, 集合的映射必须是 ICollection 或者是 IList
Student | Teacher | Result_Student | Result_Teacher | Result |
int | ![]() |
![]() |
||
Entity | ![]() |
![]() |
1. 1 - N | |
int + Entity | ![]() |
![]() |
1. 1 - N | |
int + Entity(ForeignKey) | ![]() |
![]() |
1. 1 - N | |
List | ![]() |
![]() |
1. 如果多个 Teacher 中的 StudentList 同时包含Student ,则这个Student对应的Teacher 以最后一个添加它的对象为准. 2. N - 1 |
|
Entity | Entity | Unable to determine the principal end of an association between the types 'DEMO3.Models.Teacher' and 'DEMO3.Models.Student'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations. | ||
Entity (ForeignKey) | Entity | ![]() |
![]() |
|
Entity | List | ![]() |
![]() |
1. N - 1 2. 强行指定 Student.Teacher = new Teacher(){ID = id}, 则会自动生成新的Teacher实例 3. 如果要完成在Student中正常添加Teahcer, 则可以选择 1). 在Student类中添加 TeacherID 字段, 并绑定其ID属性 2). 直接将Teacher实例绑定在 Student.Teacher上 4. Teacher 中的 StudentList 可重复添加同一个对象 |
List | List | ![]() |
![]() |
![]() |
自身引用
/// <summary> /// 上级部门Id /// </summary> [DisplayName("上级部门")] public int? ParentId { get; set; } /// <summary> /// 上级部门 /// </summary> [DisplayName("上级部门")] [ForeignKey("ParentId")] public virtual Department Parent { get; set; } /// <summary> /// 子部门 /// </summary> [DisplayName("子部门")] [InverseProperty("Parent")] public virtual ICollection<Department> Children { get; set; }
联级删除:
联级删除默认开启, 如果某个实体需要关闭的话
this.HasMany(d => d.Lodgings)
.WithRequired(l => l.Destination) .Map(l => l.MapKey("DestinationId")) //一对多并指定外键名 .WillCascadeOnDelete(false); // 关闭级联删除
EF默认开启级联删除,需要关闭的话可以在上下文的OnModelCreating方法中
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
移除这个默认约定,再在需要开启级联删除的FluentAPI关系映射中用. WillCascadeOnDelete(true) 单独开启
参考链接:
http://www.cnblogs.com/oppoic/p/ef_one-to-one_one-to-many_many-to-many_cascadedelete.html