Entity Framework Code First - Defining Relationships/Keys

◇◆丶佛笑我妖孽 提交于 2019-11-28 03:20:19
Ladislav Mrnka

This is exception caused by SQL server when you have multiple paths of cascade deletes. If you delete your PaymentTerm it will trigger cascade delete on all three relations. This will blow up when creating either SalesOrder or Invoice. EF creates by default all one-to-many relations with ON DELETE CASCADE you can remap your specific relation to not use it by:

modelBuilder.Entity<...>()
            .HasRequired(...)
            .WithMany(...)
            .HasForeignKey(...)
            .WillCascadeOnDelete(false);

Or you can turn it off globaly by removing the convention:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();   

You can get around this error on a particular migration by editing the generated Up() method with a line something like this:

AddForeignKey("dbo.Payments", "EventID", "dbo.Events", "EventID", cascadeDelete: true)

and change that cascadeDelete: value to false on the offending relationship(s).

Shimmy

Read this, I am sure this will help you find the answer.

Also, according to ScottGu's blogpost, I think in general it should be that you just create the classes as follows (I didn't read it carefully enough, so you should check it out for further details):

public class Customer
{
    public int CustomerID { get; set; }
    public int CustomerLocationID { get; set; }
    public virtual CustomerLocation Location { get; set; }
}

public class CustomerLocation
{
    public int CustomerLocationID { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!