EF Code First的循环或多个级联路径错误

时间:2013-04-01 17:50:57

标签: entity-framework ef-code-first

我使用实体框架代码优先开发了一个asp.net mvc解决方案,我收到了错误:

Introducing FOREIGN KEY constraint 'FK_dbo.Transports_dbo.Shippers_ReceiverId' on table 'Transports' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

在创建数据库的过程中启动解决方案时发生这种情况。

以下是我的模特:

public class Transport
{
    [Key]
    public int Id { get; set; }
    ...
    public int SenderId { get; set; }
    public int ReceiverId { get; set; }
    ...
    public virtual Shipper Sender { get; set; }
    public virtual Shipper Receiver { get; set; }
}

public class Shipper
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string Number { get; set; }
}

如果我评论public virtual Shipper Receiver { get; set; }那么它就可以了,所以这就是循环问题。

有没有人可以帮我解决这个问题?

1 个答案:

答案 0 :(得分:2)

对于更复杂的“自我绑定”或“多个到相同”的关系,您需要明确定义关系 - 最好使用流畅的配置。

e.g。

modelBuilder.Entity<Transport>()
    .HasRequired(at => at.Sender)
    .WithMany(a => a.TransportsAsSender)
    // .HasForeignKey(at => at.SenderId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Transport>()
    .HasRequired(at => at.Receiver)
    .WithMany(a => a.TransportsAsReceiver)
    // .HasForeignKey(at => at.ReceiverId)
    .WillCascadeOnDelete(false);

...假设您还添加:

public ICollection<Transport> TransportsAsSender { get; set; }
public ICollection<Transport> TransportsAsReceiver { get; set; }

...到Shipper

或者只是使用......

.WithMany() // and no collection navigation properties