Entityframework core 2.0 how to map Many-to-Many without creating a join table

久未见 提交于 2019-12-02 10:26:29

As commented on your question, EF Core <= 2.2 does not yet support many-to-many relationships without a join table. This is an issue tracked in the EF Core repo's backlock, and will maybe make it into version 3.0.

In your case you'll need to introduce a new table that relates to both parent tables. In this case, your model will like something like the following:

public class WorkCase
{
    public int WorkCaseId { get; set; }

    public int CaseDetailId { get; set; }

    public CaseDetail CaseDetail { get; set; }

    public ICollection<WorkCaseWorkflow> Workflows { get; set; }
}

public class Workflow
{
    public int WorkflowId { get; set; }

    public string Comment { get; set; }

    public DateTime? UpdateDate { get; set; }

    public ICollection<WorkCaseWorkflow> WorkCases { get; set; }
}

public class WorkCaseWorkflow
{
    public int WorkCaseId { get; set; }
    public WorkCase WorkCase { get; set; }

    public int WorkflowId { get; set; }
    public Workflow Workflow { get; set; }
}

Then in your DbContext subclass, override the OnModelCreating and add the following code:

protected override void OnModelCreating(ModelBuilder builder)
{
    var ww = builder.Entity<WorkCaseWorkflow>();
    ww.HasKey(w => new { w.WorkCaseId, WorkflowId });
    ww.HasOne(w => w.WorkCase)
      .WithMany(wc => wc.Workflows)
      .HasForeignKey(w => w.WorkCaseId);
    ww.HasOne(w => w.Workflow)
      .WithMany(wc => wc.WorkCases)
      .HasForeignKey(w => w.WorkflowId);
}

I'm not familiar with your model, but you can move the shared properties to the join table.


However, there is a great series of articles by @Arthur Vickers (a member in the EF Core dev team) on how to easen up many-to-many relationships:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!