Entity Framework proper way to replace collection in one to many

c# entity-framework entity-framework-6 mapping orm


Let's say that a client has many phone numbers, whereas a phone number only has one 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 at no encapsulated collection support
   public void SetPhones(params PhoneNumber[] phones) {

If I construct an EF mapping similar to this and execute it, every time I set phone numbers, new PhoneNumbers will be created but the old ones won't be deleted. I don't even disclose it on my dbcontext, and there are no other things referencing phone numbers. Is there a method to inform EF of this?Customer owns PhoneNumbers totally, thus shouldn't phone numbers that were removed from the collection be erased as well?


I am aware that there are numerous workarounds for this issue, but because it isn't an odd edge situation, what is the "correct" approach?

2/8/2017 3:02:47 PM

Accepted Answer

The similar query I had was:)

My problem was resolved by the recognizing connections response.

Note: Before changing the values and calling save, the collection must be loaded (eagerly, deliberately, or slowly) so that it can be monitored. Otherwise, you will simply be adding to the collection rather than replacing it.

For instance:

var entity = unitOfWork.EntityRepository.GetById(model.Id);
// I have something like this to load collection because
// I don't have the collection's entities exposed to the context
unitOfWork.EntityRepository.LoadCollection(entity, e => e.CollectionProperty);
entity.CollectionProperty = newCollectionValuesList;

This will just add the newly set values to the "collection table" and erase the prior collection values.

Hope that was useful.

5/23/2017 12:17:14 PM

Popular Answer


Related Questions


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