Lai*_*290 19 c# many-to-many entity-framework ef-code-first
我尝试在EF中进行测试,创建多对多的关系,因为我总是将One映射到One或One to Many,我已经在互联网上试了一个例子,这个例子适用于插入寄存器,但我无法读取寄存器
这是我的课程,我不知道是什么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>();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的背景
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");
});
}
}
Run Code Online (Sandbox Code Playgroud)
当我插入寄存器是对的
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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试选择注册显示内容时,不起作用,它只是打印什么
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Pearson p = db.Peasons.First();
Console.WriteLine(p.CoursesAttending.First().Title);
}
}
Run Code Online (Sandbox Code Playgroud)
我在数据库中检查过,寄存器存在,有什么问题?
请教我如何在代码中选择多对多的关系.
Ger*_*old 34
首先,您可能希望通过使集合虚拟来启用延迟加载:
public virtual ICollection<Course> CoursesAttending { get; set; }
public virtual ICollection<Person> Students { get; set; }
Run Code Online (Sandbox Code Playgroud)
这允许EF从中创建派生类(代理),Course
并Person
使用逻辑覆盖集合以从数据存储加载其数据.
当你这样做时,你会看到
Console.WriteLine(p.CoursesAttending.First().Title);
Run Code Online (Sandbox Code Playgroud)
将执行单独的查询来填充CoursesAttending
.
或者,或者另外,您可以决定通过急切加载来阻止往返数据库,如下所示:
Person p = db.Persons.Include(p => p.CoursesAttending).First();
Run Code Online (Sandbox Code Playgroud)
它装载Person
和的CoursesAttending
一个镜头.