gpt4 book ai didi

c# - 首先在 Entity Framework 代码中映射多对多关系

转载 作者:IT王子 更新时间:2023-10-29 04:42:33 29 4
gpt4 key购买 nike

我尝试在 EF 中进行测试,创建多对多关系,因为我总是映射一对一或一对多,我在互联网上找到了一个示例,该示例适用于插入寄存器, 但我无法读取寄存器

这是我的类(class),我不知道什么是HashSet,我在网站上得到这段代码

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>();
}
}

这是我的背景

public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }

public SchoolContext()
: base("MyDb")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().
HasMany(c => c.Students).
WithMany(p => p.CoursesAttending).
Map(
m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("PersonCourses");
});

}
}

当我插入寄存器时是正确的

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();
}
}

但是当我尝试选择 register for show content 时,是行不通的,它什么都不打印

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; }

这允许 EF 从 CoursePerson 创建派生类(代理),用逻辑覆盖集合以从数据存储。

当你这样做时,你会看到

Console.WriteLine(p.CoursesAttending.First().Title);

将执行一个单独的查询来填充CoursesAttending

或者,或者另外,您可以决定通过 eager loading 来防止往返数据库,如下所示:

Person p = db.Persons.Include(p => p.CoursesAttending).First();

一次性加载Person CoursesAttending

关于c# - 首先在 Entity Framework 代码中映射多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19646337/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com