坚持断开POCO实体 [英] Persisting disconnected POCO entities

查看:128
本文介绍了坚持断开POCO实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正与断开连接的POCO对象。

I'm working with disconnected POCO objects.

当我坚持一个对象,它工作正常!

When I persist a single object, it works fine!

当我要坚持相关对象的问题开始。

The problem starts when I want to persist related objects.

例如:

从数据层检索对象:

using (MyContext ctx = new MyContext ())
{
    return ctx.Users.First();  
}

该对象又回到了业务层和那里,我添加一些子记录,见下文(只是为了ilustrate):

This object goes back to Business layer and there, I add some child records, see below (just to ilustrate):

objectUser.Permissions.Add(new Permission());
objectUser.Permissions.Add(new Permission());

权限是导航到用户权限。

Permissions is a navigation to User Permissions.

然后,我要坚持这个objectUser回数据库,然后我做的:

And then, I want to persist this objectUser back to database, then I do:

using (MyContext ctx = new MyContext ())
{
    ctx.Users.Attach(objectUser);
    ctx.ObjectStateManager.ChangeObjectState(objectUser, System.Data.EntityState.Modified);
    ctx.SaveChanges();                       
}

但在使用内第一行,我得到的错误:与已经存在于ObjectStateManager的ObjectStateManager不能使用相同的密钥跟踪多个目标相同键的对象

But on first line inside using, I get the error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key".

有谁知道如果我做错了什么?

Does anyone know if I'm doing something wrong?

我只是想坚持对象及其相关对象。

I just want to persist objects and their related objects.

感谢您帮助我。

路易斯·古斯塔沃

我试图分离的实体,但在这种情况下,我失去所有相关的对象,我需要这些相关对象,这样我可以添加/删除。

I've tried to detach the entity, but in this case I loose all related objects, and I need these related objects so that I can add/remove.

在这之后,我想坚持他们回数据库。

After that, I wanted to persist them back to database.

我做一个愚蠢的架构??

Am I doing a stupid architecture??

路易斯·古斯塔沃

推荐答案

这里的问题似乎是,在 objectUser 对象仍连接到用于检索它的上下文从数据库中。如果您需要这个工作流程,你有两个不同的上下文定义必须卸下 objectUser 从初始上下文。这样做的一个方法是关闭对象跟踪 objectUser 上下文对象。或者,你可以手动分离从上下文的对象。

The issue here seems to be that the objectUser object is still attached to the context used to retrieve it from the database. If you require this workflow where you have two different contexts defined you must detach the objectUser from the initial context. One way to do this is to turn off object tracking on the objectUser context object. Alternately you could manually detach the object from the context.

using (MyContext ctx = new MyContext ())
{
    //EF 4.1 - ctx.Configuration.AutoDetectChangesEnabled = false;
    ctx.Users.MergeOption = MergeOption.NoTracking;

    return ctx.Users.First();  
}

博客:<一href="http://blogs.msdn.com/b/dsimmons/archive/2010/01/12/ef-merge-options-and-compiled-queries.aspx" rel="nofollow">http://blogs.msdn.com/b/dsimmons/archive/2010/01/12/ef-merge-options-and-compiled-queries.aspx

第1部分是所有关于MergeOption属性。

Part 1 is all about the MergeOption property.

这篇关于坚持断开POCO实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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