Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - How to remove multiple cascade paths in entity framework

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:

enter image description here

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:

  1. One Advert has many QUOTES, PRODUCTS:
public List<Quote> Quotes { get; set; } = new List<Quote>();
public List<Product> Products { get; set; } = new List<Product>();
  1. 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>();
  1. 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>();
  1. 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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...