问题
I am trying to define relationships between tables, but getting the following error:
Introducing FOREIGN KEY constraint 'FK_QProducts_Quotes_QuoteId' on table 'QProducts' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.Could not create constraint or index. See previous errors.
This is how my tables look like:
What I am trying to achieve:
A. Client creates an inquiry and adds products and quantities that he wish to receive a quote for
B. Suppliers quote and write prices for each product
C. Products
table contains information about quantity and QProducts
table extends it during quote with information such as prices, so I could display products under quote with both quantities and prices.
But the error is not allowing to update-database. How could I remove this error?
My relations are created by entity framework:
- One Advert has many QUOTES, PRODUCTS:
public List<Quote> Quotes { get; set; } = new List<Quote>();
public List<Product> Products { get; set; } = new List<Product>();
- One Quote has many QPRODUCTS and one ADVERT:
public Advert Advert { get; set; }
public int AdvertId { get; set; }
public List<QProduct> QProducts { get; set; } = new List<QProduct>();
- Product has one ADVERT, many QPRODUCTS:
public int AdvertId { get; set; }
public Advert Advert { get; set; }
public List<QProduct> QProducts { get; set; } = new List<QProduct>();
- QProduct has one QUOTE, one PRODUCT:
public Quote Quote { get; set; }
public int QuoteId { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
回答1:
Put simply, you cannot have cascade delete down to QProduct via multiple paths, which you do at the moment. You need to turn Cascade Delete off of one (or both, if you prefer).
For example, when configuring Product, try:
HasMany(p => p.QProducts)
.WithOne(q => q.Product)
.HasForeignKey(q => q.ProductId)
.OnDelete(DeleteBehavior.Restrict);
You'll probably need to make the FK nullable also:
public int? ProductId { get; set; }
来源:https://stackoverflow.com/questions/65514173/how-to-remove-multiple-cascade-paths-in-entity-framework