繁体   English   中英

首先在实体框架代码中映射多对多关系

[英]Mapping many to many relationship in entity framework 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>();
    }
}

这是我的背景

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

但是,当我尝试选择注册显示内容时,不起作用,它只是打印什么

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

或者,或者另外,您可以决定通过急切加载来阻止往返数据库,如下所示:

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

CoursesAttending加载Person CoursesAttending

删除类构造函数和OnModelCreating方法。 EF处理多对多关系。 你不需要做任何额外的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM