博客推荐

先学习下这几个方法

Has方法:

HasOptional:前者包含后者一个实例或者为null

HasRequired:前者(A)包含后者(B)一个不为null的实例

HasMany:前者包含后者实例的集合

With方法:

WithOptional:后者(B)可以包含前者(A)一个实例或者null

WithRequired:后者包含前者一个不为null的实例

WithMany:后者包含前者实例的集合

一对一关系

建立一对一表关系的逻辑:A的外键是B的主键,不是单独定义的B中的字段

public class Student{
public in Id {get;set;}
public virtual Teacher Teacher {get;set;}
}
public class Teacher{
[Key ,ForeignKey("Student")]]
public int Id{get;set;}
public virtual Student Student {get;set;}
}
//这个ForeignKey的属性还挺不好理解的,正向理解就挺简单的:下面的这个id作为表Student的外键
//如果这样写
public int DestinationId { get; set; }
[ForeignKey("DestinationId")]
public Destination Destination { get; set; }
//就表示,下面的表的外键是本表的DestinationId
//分析下两种语法,一种是下面的表的外键是括号中的字段,上一种语法是下面的id是是括号中表的外键
//这种属性怎么能写这么复杂?可能是考虑到易用性吧,真灵活,正常人还是会用Fluent AP这种符合人的思维的语法
//上面的是用Data Annotations表示法,下面用Fluent API表示法展示一下
Teacher.HasRequired(a =>a.Student).WithOptional(a=>a.Teacher);

一对多的关系

public class Student{
public in Id {get;set;}
public virtual Teacher Teacher {get;set;}
}
public class Teacher{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Equipment()
{
Students= new HashSet<Student>();
}
public int Id{get;set;}
public virtual ICollection<Student> Students {get;set;}
}
//在OnModelCreating方法中定义
modelBuilder.Entity<Teacher>()
.HasMany(e => e.Students )
.WithRequired(e => e.Teacher )
.WillCascadeOnDelete(true); // 设置级联删除

多对多的关系

public class Student{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Student()
{
Teachers= new HashSet<Teacher>();
}
public in Id {get;set;}
public virtual ICollection<Teacher> Teachers {get;set;}
}
public class Teacher{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Teacher()
{
Students= new HashSet<Student>();
}
public int Id{get;set;}
public virtual ICollection<Student> Students {get;set;}
}
//在OnModelCreating方法中定义
modelBuilder.Entity<Teacher>()
.HasMany(e => e.Students )
.WithMany(e => e.Teachers )
.WillCascadeOnDelete(true); // 设置级联删除
05-27 13:14