是否可以检查对象是否已经附加到Entity Framework中的数据上下文? [英] Is is possible to check if an object is already attached to a data context in Entity Framework?

查看:184
本文介绍了是否可以检查对象是否已经附加到Entity Framework中的数据上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试通过 context.AttachTo(...)

附加一个已经附加到给定上下文的对象时,我收到以下错误:


ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager不能跟踪具有相同键的多个对象。


有没有办法达到以下一些目的:



context.IsAttachedTo(...)



干杯! / p>

编辑:



Jason概述的扩展方法很接近,为我的情况工作。



我正在尝试使用另一个问题的答案中列出的方法进行一些工作:



如何使用Linq to Entities *从表中删除一行或多行????首先检索行?



我的代码看起来有点像这样:

  var user = new User(){Id = 1}; 
context.AttachTo(Users,user);
comment.User = user;
context.SaveChanges();

这个工作正常,除了当我为其他用户使用相同的方法,附加虚拟用户对象。因为我之前已经附加了这个虚拟用户对象,所以失败。我如何检查这个?

解决方案

这是我结束的,这非常好的工作:

  public static void AttachToOrGet< T>(此ObjectContext上下文,string entitySetName,ref T entity)
其中T:IEntityWithKey
{
ObjectStateEntry条目;
//跟踪是否需要执行附加
bool attach = false;
if(
context.ObjectStateManager.TryGetObjectStateEntry

context.CreateEntityKey(entitySetName,entity),
输入条目


{
//如果需要,重新附加
attach = entry.State == EntityState.Detached;
//将发现的实体发送到ref
entity =(T)entry.Entity;
}
else
{
//第一次附加
attach = true;
}
if(attach)
context.AttachTo(entitySetName,entity);
}

您可以按如下方式调用:

  User user = new User(){Id = 1}; 
II.AttachToOrGet< Users>(Users,ref user);

这个工作非常好,因为它就像 context.AttachTo(... )除了你可以使用每次上面引用的ID技巧。您最终会得到先前连接的对象或您附加的对象。在上下文中调用 CreateEntityKey 确保它是好的和通用的,即使使用复合密钥也不会进一步编码(因为EF可以为我们做这个)。


I am getting the following error when trying to attach an object that is already attached to a given context via context.AttachTo(...):

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Is there a way of achieving something along the lines of:

context.IsAttachedTo(...)

Cheers!

Edit:

The extension method Jason outlined is close, but it doesn't work for my situation.

I am trying to do some work using the method outlined in the answer to another question:

How do I delete one or more rows from my table using Linq to Entities *without* retrieving the rows first?

My code looks a bit like this:

var user = new User() { Id = 1 };
context.AttachTo("Users", user);
comment.User = user;
context.SaveChanges();

This works fine, except when I do something else for that user where I use the same method and try to attach a dummy User object. This fails because I have previously attached that dummy user object. How can I check for this?

解决方案

Here's what I ended up with, which works very nicely:

public static void AttachToOrGet<T>(this ObjectContext context, string entitySetName, ref T entity)
    where T : IEntityWithKey
{
    ObjectStateEntry entry;
    // Track whether we need to perform an attach
    bool attach = false;
    if (
        context.ObjectStateManager.TryGetObjectStateEntry
            (
                context.CreateEntityKey(entitySetName, entity),
                out entry
            )
        )
    {
        // Re-attach if necessary
        attach = entry.State == EntityState.Detached;
        // Get the discovered entity to the ref
        entity = (T)entry.Entity;
    }
    else
    {
        // Attach for the first time
        attach = true;
    }
    if (attach)
        context.AttachTo(entitySetName, entity);
}

You can call it as follows:

User user = new User() { Id = 1 };
II.AttachToOrGet<Users>("Users", ref user);

This works very nicely because it's just like context.AttachTo(...) except you can use the ID trick I cited above each time. You end up with either the object previously attached or your own object being attached. Calling CreateEntityKey on the context makes sure it's nice and generic and will work even with composite keys with no further coding (because EF can already do that for us!).

这篇关于是否可以检查对象是否已经附加到Entity Framework中的数据上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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