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.
希望对您有所帮助.
这篇关于实体框架以一对多替换集合的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架以一对多替换集合的正确方法
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01