2

我首先使用实体​​框架代码开发了一个 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; }那么它可以工作,所以这是循环问题。

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

4

1 回答 1

2

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

例如

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
于 2013-04-01T19:42:25.367 回答