EF核心中的多对多关系问题

时间:2018-11-08 15:17:54

标签: asp.net-core entity-framework-core

我正在尝试在实体Project和实体Resource之间建立多对多关系。我创建了一个关系实体:ProjectResource。我已经使用流利的API建立了这样的关系:

modelBuilder.Entity<ProjectResource>()
    .HasKey(pr => new { pr.ProjectId, pr.ResourceId });

modelBuilder.Entity<ProjectResource>()
    .HasOne(pr => pr.Project)
    .WithMany(p => p.ProjectResources)
    .HasForeignKey(pr => pr.ProjectId);

modelBuilder.Entity<ProjectResource>()
    .HasOne(pr => pr.Resource)
    .WithMany(r => r.ProjectResources)
    .HasForeignKey(pr => pr.ResourceId);

这是我的课程ProjectResources的简短定义(我仅包括这种关系):

public class Resource
{
    public Guid DepartmentId { get; set; }
    public Department Department { get; set; }

    public Guid? ManagerId { get; set; }
    public Resource Manager { get; set; }

    public ICollection<Resource> Resources { get; set; }
    public ICollection<ProjectResource> ProjectResources { get; set; }
    public ICollection<ChangeLog> ChangeLogs { get; set; }
    public ICollection<Requirement> Requirements { get; set; }
    public ICollection<UseCase> UseCases { get; set; }  
}

public class Project
{
    public Guid ResponsibleId { get; set; }
    public Resource Responsible { get; set; }

    public ICollection<ProjectResource> ProjectResources { get; set; }
    public ICollection<BusinessNeed> BusinessNeeds { get; set; }
    public ICollection<SuccessCriteria> SuccessCriterias { get; set; }
    public ICollection<Requirement> Requirements { get; set; }
    public ICollection<UseCase> UseCases { get; set; }
    public ICollection<ChangeLog> ChangeLogs { get; set; }
    public ICollection<GlossaryWord> GlossaryWords { get; set; }
}

public class ProjectResource
{
    public Guid ProjectId { get; set; }
    public Project Project { get; set; }
    public Guid ResourceId { get; set; }
    public Resource Resource { get; set; }
}

我已经研究了问题,但似乎找不到解决方案。我已经完成了here中描述的指南。

我遇到以下错误:

  

在表'ProjectResources'上引入FOREIGN KEY约束'FK_ProjectResources_Resources_ResourceId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

我到底在做什么错?

1 个答案:

答案 0 :(得分:1)

问题是由ResourceProject之间存在的required(因此cascade delete)之间存在一对多关系引起的,由Responsible / ResponsibleId中的Project个属性。

以下是从ResourceProjectResource的多个级联路径:

Resource (Id) -> (ResponsibleId) Project (Id) -> (ProjectId) ProjectResource
Resource (Id) -> (ResourceId) ProjectResource

解决多个级联路径的唯一方法是通过关闭至少一种关系的级联删除并手动或通过数据库触发器来处理删除来打破循环。

对于此具体模型,可能最简单的方法是针对Resource-> Project关系关闭删除级联:

modelBuilder.Entity<Project>()
    .HasOne(p => p.Responsible)
    .WithMany()
    .OnDelete(DeleteBehavior.Restrict);