Entity Framework 导航属性(2)
2024-10-19 01:27:16
1.学校
[Table("School")]
public partial class School
{
public School()
{
Students = new List<Student>();
Teachers = new List<Teacher>();
}
[Key]
public string SchoolId { get; set; } public string Name { get; set; } public virtual ICollection<Student> Students { get; set; } public virtual ICollection<Teacher> Teachers { get; set; }
}
2.学生
[Table("Student")]
public partial class Student
{
public Student()
{
Teachers = new List<Teacher>();
}
[Key]
public string StudentId { get; set; } public string Name { get; set; } public string PhoneId { get; set; } public string SchoolId { get; set; } public virtual School School { get; set; } public ICollection<Teacher> Teachers { get; set; }
}
3.教师
[Table("Teacher")]
public class Teacher
{
public Teacher()
{
Students = new List<Student>();
}
[Key]
public string TeacherId { get; set; } public string Name { get; set; } public string PhoneId { get; set; } public string SchoolId { get; set; } public virtual School School { get; set; } public virtual ICollection<Student> Students { get; set; }
}
上面三个数据表映射成的实体类,关系是学校有多个学生和老师,每个学生和老师互相对应多个
关系配置在DbContext的OnModelCreating方法中配置
一对多
modelBuilder.Entity<Student>()
.HasRequired(a => a.School)
.WithMany(a => a.Students)
.HasForeignKey(a=>a.StudentId);
modelBuilder.Entity<Teacher>()
.HasRequired(a => a.School)
.WithMany(a => a.Teachers)
.HasForeignKey(a => a.TeacherId);
多对多
modelBuilder.Entity<Teacher>()
.HasMany(a => a.Students)
.WithMany(a => a.Teachers)
.Map
(
a =>
{
a.MapLeftKey("TeacherId");
a.MapRightKey("StudentId");
a.ToTable("Teacher_Student");
} );
最新文章
- 第三条:用私有构造器或者枚举类型强化Singleton属性
- php把错误日志输入到文件里。
- UIButton在不同状态下显示不同背景色
- hrbustoj 1161:Leyni(树状数组练习)
- js方法控制html表格的增加和删除
- 黑马程序员_<;<;IO流基本操作(Writer,Reader)>;>;
- maven添加oracle jdbc依赖
- windows命令行模式下无法打开python程序解决方法
- 迭代子模式(Iterator)
- com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector APPARENT DEADLOCK
- Python实现网站模拟登陆
- Django SNS 微博项目开发
- Mysql SQL分组取每组前几条记录
- P1233 木棍加工 dp LIS
- Linux(Centos7)下搭建SVN服务器
- 组队项目——黄金点(叶雨&;王浩)
- php-xdebug(安装)
- 【程序练习】——ini格式转换为xml格式
- day02(继承,重写,this,super,final,抽象类)
- 星空灯改装成USB供电