Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set collection to modified Entity Framework

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;}
}
like image 406
Chazt3n Avatar asked Sep 28 '22 17:09

Chazt3n


2 Answers

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

like image 187
Gert Arnold Avatar answered Oct 05 '22 07:10

Gert Arnold


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();
  }
like image 20
Chazt3n Avatar answered Oct 05 '22 05:10

Chazt3n