Mediator
Mediator

Reputation: 15378

How delete collection?

 var main = (from d in db.Discounts where d.Id == discount.Id && d.UserId == userId select d).FirstOrDefault();
main.Address = "new address";
main.TermsStocks.Clear(); // I need clear collection and add new object.

            foreach (var termsStock in terms)
            {
                main.TermsStocks.Add(new TermsStock() { Id = Guid.NewGuid(), MainId = main.Id, Title = termsStock.Title });
            }
db.SaveChanges(); 

and I have error:

The operation failed. Unable to change the link because one or more properties of the foreign key values ​​do not allow NULL. If you change the connection property of the respective foreign key set to NULL. If the foreign key value does not support NULL, must be defined a new relationship, the foreign key property should be set to another value other than NULL, or to remove unbound object.

how to remove the entire collection and save a new one?

Upvotes: 0

Views: 98

Answers (2)

daryal
daryal

Reputation: 14919

I think TermsStock object has a non nullable foreign key of Discount. Then it is not possible to have a TermsStock object without a Discount. What you are trying to do is not possible in this manner.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273179

You will have to remove those items form the database as well, not just from the nav property.

Roughly:

// main.TermsStocks.Clear(); 
foreach (var item in main.TermsStocks)
{
    db.TermsStocks.Remove(item);
}

Upvotes: 1

Related Questions