简体   繁体   English

实体框架5不更新两个实体中的导航属性

[英]Entity Framework 5 not updating navigation properties in both entities

I have updated a project to use the new Entity Framework shipped with VS2012 . 我已经更新了一个项目,以使用VS2012附带的新Entity Framework However, I ran into some issues 'cause of which my code is throwing exceptions. 但是,我遇到了一些问题,因为我的代码引发了异常。

In the VS2010 version of Entity Framework , I was able to create or modify an Entity and use its navigation properties before calling SaveChanges() VS2010版本的Entity Framework ,我能够在调用SaveChanges()之前创建或修改Entity并使用其导航属性。

For example: A Navigation property of a client having a collection of Invoices. 例如:具有发票集合的客户端的Navigation属性。

Client c = new Client();
Invoice I = new Invoice();
c.Invoices.Add(I);

I would then be able to use Invoice.Client somewhere in my code before actually saving it without issue. 这样,我便可以在代码中的某个地方使用Invoice.Client ,然后真正保存它而不会出现问题。 Now Invoice.Client == null . 现在Invoice.Client == null

Similarly in setting I.Client = C , I does not show up under C.Invoices 类似地,在设置I.Client = CI不会出现在C.Invoices

What am I missing here or is this just simply how Entity Framework 5 is? 我在这里缺少什么,或者这仅仅是Entity Framework 5

EDIT 编辑

In VS2010 , I Created a new project, added the same DataSource and the following code worked as expected: VS2010 ,我创建了一个新项目,添加了相同的DataSource ,并且以下代码按预期工作:

Client C = new Client();
C.Name = "Test";
Invoice I = new Invoice();
C.Invoices.Add(I);
MessageBox.Show(I.Client.Name);

Did the exact same thing in VS2012 and no dice. VS2012做了完全一样的事情,没有骰子。

In your above example you aren't actually attached to the context. 在上面的示例中,您实际上并没有附加到上下文。

Back-references for EF are only populated via a process called fixups which runs as a result of DetectChanges which in turn is triggered by (in your case) IDbSet<>.Add() EF的反向引用仅通过一个称为fixup的过程进行填充,该过程是DetectChanges的结果,而DetectChanges又由IDbSet <>。Add()触发。

If you modify your code to attach Client to the context before adding an invoice to it you should see the expected behaviour 如果您修改代码以在将发票添加到客户端之前将客户端附加到上下文,则应该会看到预期的行为

EDIT: 编辑:

I haven't really used this feature with DB First (.edmx) but you can enable it by using the below model type in 2010. 我尚未在DB First(.edmx)中真正使用此功能,但是您可以在2010年使用以下模型类型来启用它。

This model type has been removed in 2012 as STEs have been deprecated . 由于不推荐使用STE,因此该模型类型已在2012年删除。 (Although my understanding is that they still work for backward compatibility so if you were to upgrade a project from 2010-2012 you would still be able to use that model) (尽管我的理解是,它们仍可用于向后兼容,因此,如果您要从2010-2012升级项目,您仍然可以使用该模型)

自我追踪实体

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM