C# 首先在实体框架代码中映射多对多关系
我正在尝试在EF中进行测试,创建一个多对多关系,因为我总是将一对一或一对多映射,我在互联网上得到了一个用于尝试的示例,该示例用于插入寄存器,但我无法读取寄存器 这是我的类,我不知道什么是HashSet,我在网站上得到了这些代码C# 首先在实体框架代码中映射多对多关系,c#,entity-framework,ef-code-first,many-to-many,C#,Entity Framework,Ef Code First,Many To Many,我正在尝试在EF中进行测试,创建一个多对多关系,因为我总是将一对一或一对多映射,我在互联网上得到了一个用于尝试的示例,该示例用于插入寄存器,但我无法读取寄存器 这是我的类,我不知道什么是HashSet,我在网站上得到了这些代码 public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get;
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Course> CoursesAttending { get; set; }
public Person()
{
CoursesAttending = new HashSet<Course>();
}
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public ICollection<Person> Students { get; set; }
public Course()
{
Students = new HashSet<Person>();
}
}
但当我尝试为显示内容选择“注册”时,它不起作用,只是不打印任何内容
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Pearson p = db.Peasons.First();
Console.WriteLine(p.CoursesAttending.First().Title);
}
}
我查过数据库,有注册,有什么问题
请先教我如何在与代码的多对多关系中进行选择。删除类构造函数和OnModelCreating方法。
EF处理多对多关系。您不需要做任何额外的操作。首先,您可能希望通过使集合虚拟化来启用延迟加载: 将执行一个单独的查询来填充
CoursesAttending
或者,或者另外,您可以决定通过如下方式紧急加载来防止数据库的往返:
它一次加载
人
和课程
。太棒了!这是工作!!所以为什么Include用于快速选择?我不明白如何使用includea,因为这个词说,Include
在查询中包含属性。通常,使用一个SQL查询(带连接)比在单独查询中获取对象并查询其关联对象更有效。默认情况下,使用数据注释可以提供一个时髦的命名约定,并提供流畅的api代码,这种不必要的命名是可以避免的。这个答案对我来说毫无帮助。如果在多对多关系中的导航属性上使用.Add()
,EF会自动更新相应的联接表吗?@Celdor EF当然会更新相应的联接表。
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Course math = new Course();
Course history = new Course();
Course biology = new Course();
math.Title = "Math";
history.Title = "History";
biology.Title = "Biology";
db.Courses.Add(math);
db.Courses.Add(history);
db.Courses.Add(biology);
Person john = new Person();
john.FirstName = "John";
john.LastName = "Paul";
john.CoursesAttending.Add(history);
john.CoursesAttending.Add(biology);
db.People.Add(john);
db.SaveChanges();
}
}
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Pearson p = db.Peasons.First();
Console.WriteLine(p.CoursesAttending.First().Title);
}
}
public virtual ICollection<Course> CoursesAttending { get; set; }
public virtual ICollection<Person> Students { get; set; }
Console.WriteLine(p.CoursesAttending.First().Title);
Person p = db.Persons.Include(p => p.CoursesAttending).First();