c# - Entity Framework proper way to replace collection in one to many -


suppose customer has many phone numbers , phone number has 1 customer.

public class phonenumber : ivalueobject {   public string number {get; set;}   public string type {get; set;} }  public class customer : ientity {    public icollection<phonenumber> phones {get; private set;} //ew @ no encapsulated collection support    public void setphones(params phonenumber[] phones) {        this.phones.clear();        this.phones.addrange(phones);    } } 

if ef mapping , run it, every time set phone numbers create new phonenumbers not delete old ones. there no other entities referencing phone numbers, don't expose on dbcontext, there way tell ef customer owns phonenumbers , therefore if phone numbers removed collection should deleted?

proof

i realize there's dozen ways hack around problem, isn't weird edge case, what's "right" way handle this.

i had exact same question :)

this answer on identifying relationships solved issue.

note: have load collection (eagerly, explicitly or lazily) can tracked before setting new values , calling save. otherwise not replacing collection but, adding it.

for example:

var entity = unitofwork.entityrepository.getbyid(model.id); // have load collection because // don't have collection's entities exposed context unitofwork.entityrepository.loadcollection(entity, e => e.collectionproperty); entity.collectionproperty = newcollectionvalueslist; unitofwork.save(); 

this remove previous collection values 'collection table' , add newly set values.

hope helps.


Comments