实体框架断开图和导航属性 [英] Entity Framework disconnected graph and navigation property

查看:206
本文介绍了实体框架断开图和导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与实体框架六典第一,流利的API工作。我有一个参观VisitPage(1访问有许多VisitPage对象)之间有很多关系。这是POCO类的简化版本:

I'm working with Entity Framework 6 Code First and Fluent API. I have a one to many relationship between Visit and VisitPage (1 Visit has many VisitPage objects). This is the simplified version of the POCO classes:

访问:ID(身份),UrlReferrer,页面。
VisitPage :ID(身份),名称,访问,VisitId

Visit: Id (identity), UrlReferrer, Pages. VisitPage: Id (identity), Name, Visit, VisitId

首先,我创建了一个访问对象,并添加VisitPage反对。然后,我将它们插入到数据库。直到此时一切正常确定。观察:在VisitPage VisitId属性插入后自动设置(需要从数据库的标识值,并将属性设置)

First, I create a Visit object and add a VisitPage object to it. Then, I insert them into the DB. Until this point everything works OK. Observation: VisitId property in VisitPage is automatically set after insertion (it takes the identity value from DB and sets the property).

然后,在断开连接的环境,我想补充一个新页面访问(我不从DB访对象,这就是我的意思是断开的环境)。这个新的网页是指相同的访问对象,但我不会设置VisitId属性,因为我认为应该EF设置根据访问属性。这就是问题所在,EF不设置它,事实上,它抛出一个异常说,访问财产和VisitId属性的值不匹配。我期待的EF将是能够做到这一点的引擎盖下(在DetectChanges方法为例),但事实并非如此。

Then, in a disconnected environment, I add a new page to the visit (I don't get the Visit object from the DB, that's what I mean by disconnected environment). This new page is referring the same visit object but I'm not setting the VisitId property because I think that EF should set it based on the Visit property. And that's the problem, EF doesn't set it and, in fact, it throws an exception saying that the value of Visit property and VisitId property doesn't match. I was expecting that EF was going to be able to do this under the hood (in the DetectChanges method for example) but it doesn't.

异常消息:

一个参照完整性约束冲突发生了:'VisitId的属性值(S)在关系不匹配'VisitPage.VisitId的另一端的属性值(S)的一端。

A referential integrity constraint violation occurred: The property value(s) of 'VisitId' on one end of a relationship do not match the property value(s) of 'VisitPage.VisitId' on the other end.

那么,我该如何解决这个问题?我看到了两个可能的解决方案:
1)连接的环境中工作 - >从EF获得访问对象,然后添加页面对象。在这种情况下EF更新VisitId价值和它的作品。
2)设置VisitId后手动设置访问对象。

So, how do I solve this? I see two possible solutions: 1) Work in a connected environment --> get the Visit object from EF and then add the page object. In this case EF updates VisitId value and it works. 2) Set VisitId manually after setting the Visit object.

我希望我已经足够清晰。如果没有,请让我知道。

I hope I've been clear enough. If not, please let me know.

推荐答案

做这一点

visitPage.VisitId = VisitPage.Visit.Id;
visitPage.Visit = null;

context.Visits.Attach(visitPage.Visit);

context.Entry(visitPage.Visit).State = EntityState.Unchanged;

这篇关于实体框架断开图和导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆