0

I am trying to delete an entity which is added to the context without saving the changes. I am getting FK constraint errors. The entity is temporary which need not to be saved to the database.

This is how I am adding the entity

var productSalesRight = new ProductSupplierSalesRight
                            {
                                Product = product,
                                ProductId = product.ProductId,
                                SalesRightTypeId = countries.FirstOrDefault().SalesRightTypeId,
                                SalesRightType = countries.FirstOrDefault().SalesRightType,
                                Countries = ct
                            };

product.ProductSupplierSalesRights.Add(productSalesRight);

This is what I am doing in my code to delete

 _context.Entry(productSalesRight).State = EntityState.Deleted;
 product.ProductSupplierSalesRights.Remove(productSalesRight)

Is there a right way of deleting an entity?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alan B
  • 2,219
  • 4
  • 32
  • 62

1 Answers1

0

You should detach your temporary entity record if you don't want to continue inserting it to the database.

Refer to ObjectContext.Detach Method (Object)

_context.Detach(productSalesRight);
jegtugado
  • 5,081
  • 1
  • 12
  • 35