Reputation: 9342
I develop an asp.net mvc solution with Entity Framework Code First and I got the error:
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.
This occurred when starting the solution in the process of creation of the database.
Here are my models:
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; }
}
If I comment the public virtual Shipper Receiver { get; set; }
then it works so this is the cyclic problem.
Does anyone can help me on this problem?
Upvotes: 2
Views: 331
Reputation: 14302
For more complex 'self-bound' or 'multiple to same' relationships, you need to explicitly define the relationships - best using fluent configuration.
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);
...that assumes you also add:
public ICollection<Transport> TransportsAsSender { get; set; }
public ICollection<Transport> TransportsAsReceiver { get; set; }
...to the Shipper
Or just use...
.WithMany() // and no collection navigation properties
Upvotes: 2