Set collection to modified Entity Framework

c# entity-framework-6

Question

How can I set a collection to modified in the same way that I would do

_context.Entry(thing).Property(x => x.MyProperty).isModified = true;

like:

_context.Entry(thing).Collection(x => x.MyCollection).isModified = true;

EDIT: The purpose of this, is that my collection is a list of objects stored in a lookup table. I will only have a list of stubs with their id's in this collection and I would like to update the relationships without messing with the audit values and whatever else is contains within the lookup objects. For instance, a contact will have multiple contact types, which for whatever reason are complex objects in this scenario. I want to be able to add and remove types using only the FKs and let EF handle the relationship fixups.

public class Contact
{
   public int Id {get;set;}
   public list<ContactTypes> ContactTypes {get;set;}
   //audit values/other properties
}

public class ContactType
{
   public int Id {get;set;}
   public string Value {get;set;}
}
1
4
2/4/2019 11:44:41 PM

Accepted Answer

context.Entry represents a single entity, never a collection. So you have to loop through the collection and mark each entity as modified.

3
6/5/2015 2:47:54 PM

Popular Answer

If you have a list of ForeignKey objects, you probably know how frustrating it is to force EF's Relationship Fixup on them. Here's slick way to do that.

public void SetContactTypesToUnchanged(Contact contact)
  {
    contact.ContactTypes.Each(type => _context.Entry(type).State = EntityState.Unchanged);
    _context.SaveChanges();
  }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow