如何获得多对多关系的相关数据?

时间:2019-07-17 14:08:21

标签: many-to-many ef-core-2.2

我有具有多对多关系的Project和Programmer模型:

public class Project
{
    public Project()
    {
        ProjectProgrammers = new HashSet<ProjectProgrammer>();
    }
    public int ProjectID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual ICollection<ProjectProgrammer> ProjectProgrammers { get; set; }
}

public class Programmer
{
    public Programmer()
    {
        ProjectProgrammers = new HashSet<ProjectProgrammer>();
    }

    public int ProgrammerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DisplayName { get; set; }

    public virtual ICollection<ProjectProgrammer> ProjectProgrammers { get; set; }
}

有一个模型ProjectProgrammer:

public class ProjectProgrammer
{
    public int ProjectID { get; set; }
    public virtual Project Project { get; set; }

    public int ProgrammerID { get; set; }
    public virtual Programmer Programmer { get; set; }
}

配置:

        modelBuilder.Entity<ProjectProgrammer>()
            .HasKey(pp => new { pp.ProjectID, pp.ProgrammerID });

        modelBuilder.Entity<ProjectProgrammer>()
            .HasOne(pp => pp.Project)
            .WithMany(p => p.ProjectProgrammers)
            .HasForeignKey(pp => pp.ProjectID);

        modelBuilder.Entity<ProjectProgrammer>()
            .HasOne(pp => pp.Programmer)
            .WithMany(p => p.ProjectProgrammers)
            .HasForeignKey(pp => pp.ProgrammerID);

当我尝试使用Include()和Theninclude()加载相关数据时:

    public async Task<IEnumerable<Project>> ListAsync()
    {
        return await _context.Projects.Include(p => p.ProjectProgrammers)
                                      .ThenInclude(pp => pp.Programmer)
                                      .ToListAsync();
    }

我只得到第一条记录,其中包含不完整的程序员信息:

[{"projectID":100,"name":"Project1","description":"Desc","projectProgrammers":[{"projectID":100

1 个答案:

答案 0 :(得分:0)

我通过向导航属性之一添加[JsonIgnore]属性解决了此问题。详细信息:http://ericsmasal.com/2018/01/04/ef-core-and-defeating-the-self-referencing-loop/