在 EF 中添加具有现有父级的新记录
我使用实体框架,并在层次结构中包含一组 3 个不同的表。思考公寓单元 ->公寓大楼 ->所有者组织。每个在数据库中都有一个主键和一个其所有者的外键。当我构建 EF 模型时,它为每个模型创建了属性。事实上,保存每个实例的新实例非常容易。例如,我还了解到,要添加新单位,我首先需要添加一个组织,将其添加到新的综合体,然后在保存之前将其添加到新单位。有点工作,但这是有道理的。
我现在感到困惑的是,我有一个新的公寓单元,但它住在一个现有的综合体中。我可以使用适当的属性构建一个新的复杂对象,并将其附加到新单元,但是当我去保存该单元时,框架会在 ApartmentComplex 表中抛出主键冲突,因为它正在尝试添加我将其附加为一个新的综合体,而不是现有的综合体。
对我来说,解决方法似乎是首先检索复合体的一个新实例,而不是构建一个实例 - 实际上,让 EF 代替我构建它 - 但这意味着另一次往返,对我来说似乎有点矫枉过正。有没有更简单的方法来保存我的新公寓单元?
I'm using Entity Framework with a set of 3 different tables, in a hierarchy. Think ApartmentUnit -> ApartmentComplex -> OwnerOrganization. Each has a primary key, and a foreign key to its owner, in the database. When I built the EF model, it created properties for each of those. Indeed, saving new instances of each is pretty easy. I also learned, for example, that to add a new unit, I first need to add an organization, add it to a new complex, then add that to the new unit before saving. A bit of work, but it makes sense.
Where I am confused now is, I have a new apartment unit, but it lives in an existing complex. I can build up a new complex object with the appropriate properties, and attach it to the new unit, but when I go to save the unit, the framework spits up a primary key violation in the apartmentComplex table, as it is trying to add the complex I attached as a NEW complex, not an existing one.
The workaround to me seems to be go and retrieve a new instance of the complex first, instead of building one - in effect, letting the EF build it instead of me - but that would mean another round-trip and seems like overkill to me. Is there a simpler way to save my new Apartment Unit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在不访问数据库的情况下创建现有的复合体,但必须在保存之前将其附加到上下文。
You can create the existing complex without going to the DB but you must attach it to the context before you save.