繁体   English   中英

实体具有两个属性,它们都以一对多关系引用相同的实体类型

[英]Entity has two properties which both reference the same entity type in one-to-many relationship

这似乎是最常见的关系,但是由于某种原因,我无法使代码优先EF正常工作。 当我运行下面的代码时,出现以下错误:

* {“在表'Recordings'上引入FOREIGN KEY约束'Recording_RecordingLocation'可能会导致循环或多个级联路径。请指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。\\ r \\ n无法创建约束。请参阅。先前的错误。“} *

我已经研究了SO和其他地方,但无法弄清楚。 我一定是中风,所以如果这是重复的,我深表歉意。 我不认为这是因为我发现的所有其他参考问题都是针对多对多关系...多对一的。

我的情况很简单...

我有一个实体(Recording),它具有两个必填属性RecordingLocation和EditingLocation,它们都是相同的WorkLocation类型。 每个Recording都有一个RecordingLocation和一个EditingLocation (不是多对多) 我还具有必需的导航属性。

每个WorkLocation是独立的,并没有与Recording内在链接-它只是在该Recording上进行某些工作的物理位置。 因此,当我删除记录时,我不想删除关联的工作位置。

public class Recording
{
    [Key]
    public virtual int Id { get; set; }

    //... other properties not shown here

    public virtual int RecordingLocationId { get; set; }
    public virtual WorkLocation RecordingLocation { get; set; }

    public virtual int EditingLocationId { get; set; }
    public virtual WorkLocation EditingLocation { get; set; }
{


public class WorkLocation
{
    [Key]
    public virtual int Id { get; set; }
    public virtual WorkLocationType Type { get; set; }
    public virtual string Description { get; set; }
    public virtual LogicalStatus Status { get; set; }
}

// I'll use this on the front-end to filter a selection list
// but don't necessarily assume a Work Location is bound to only items of this type
public enum WorkLocationType
{
    RecordingLocation,
    EditingLocation,
    MasteringLocation
}

我缺少什么才能使它正常工作?

您的导航属性RecordingLocationEditingLocation是必需的,因为相应的外键属性不可为空。 按照惯例,EF假定级联删除对于必需的一对多关系是活动的,如果您有多个这样的关系引用同一张表,则会导致问题。

您必须禁用级联删除(您的业务逻辑似乎也需要这样做),这只能在Fluent API中进行:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Recording>()
            .HasRequired(r => r.RecordingLocation)
            .WithMany()
            .HasForeignKey(f => f.RecordingLocationId)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Recording>()
            .HasRequired(r => r.EditingLocation)
            .WithMany()
            .HasForeignKey(f => f.EditingLocationId)
            .WillCascadeOnDelete(false);
    }
}

暂无
暂无

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

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