实体框架以一对多替换集合的正确方法

Entity Framework proper way to replace collection in one to many(实体框架以一对多替换集合的正确方法)
本文介绍了实体框架以一对多替换集合的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个客户有很多电话号码,而一个电话号码只有一个客户.

Suppose a customer has many phone numbers and a phone number has only 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) {
       this.phones.Clear();
       this.phones.AddRange(phones);
   }
}

如果我像这样进行 EF 映射并运行它,每次我设置电话号码时,它都会创建新的 PhoneNumbers,但不会删除旧的.没有其他实体引用电话号码,我什至没有在我的 dbcontext 上公开它,有没有办法告诉 EF Customer 完全拥有 PhoneNumbers,因此如果电话号码已从集合中删除,它们应该被删除吗?

If I do an EF mapping like this and run it, every time I set phone numbers it will create new PhoneNumbers but not delete the old ones. There are no other entities referencing phone numbers, I don't even expose it on my dbcontext, is there a way to tell EF that Customer owns PhoneNumbers completely and therefore if phone numbers were removed from the collection they should be deleted?

我意识到有十几种方法可以解决这个问题,但这并不是一个奇怪的极端情况,处理这个问题的正确"方法是什么.

I realize that there's a dozen ways to hack around this problem, but this isn't a weird edge case, what's the "right" way to handle this.

推荐答案

我也有同样的问题 :)

I had the exact same question :)

识别关系上的这个答案解决了我的问题.

This answer on identifying relationships solved my issue.

注意:您必须(急切地、显式地或延迟地)加载集合,以便在设置新值和调用 save 之前对其进行跟踪.否则,您将不会替换集合,而只是将其添加到其中.

Note: You have to load the collection (eagerly, explicitly or lazily) so that it can be tracked before setting the new values and calling save. Otherwise you will not be replacing the collection but, just be adding to it.

例如:

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;
unitOfWork.Save();

这将从集合表"中删除以前的集合值,只添加新设置的值.

This will remove the previous collection values from the 'collection table' and only add the newly set values.

希望对您有所帮助.

这篇关于实体框架以一对多替换集合的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)