0
 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?

Mediator
  • 14,951
  • 35
  • 113
  • 191
  • 1
    possible duplicate of [Entity Framework 4 Delete Object from entity collection](http://stackoverflow.com/questions/4922228/entity-framework-4-delete-object-from-entity-collection) – Ladislav Mrnka Apr 02 '12 at 08:03

2 Answers2

1

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);
}
H H
  • 263,252
  • 30
  • 330
  • 514
0

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.

daryal
  • 14,643
  • 4
  • 38
  • 54