2

As you can see from the code below i use AsNoTracking to get my object. I then even use ObjectSateManager to see what is going on and i can see nothing being tracked in the l* collections and yet i still get

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

Any ideas?

==========================================
BasketRepository repo = new BasketRepository();

            var ba = repo.GetById(8);

            var bpro = new BasketProduct(ba, ba.BasketProducts.First().Product, 3);

            repo.AddToBasket(bpro);
           repo.Save();

==================================

    public Basket GetById(int basketId)
    {
        // eager-load product info
        var basket = dbContext.Baskets.Include("BasketProducts")
                                      .Include("BasketProducts.Product.Brand").AsNoTracking().SingleOrDefault(b => b.BasketId == basketId);;
        return basket;
    }

======================================

  public void AddToBasket(BasketProduct product)
    {
        var ctx = ((IObjectContextAdapter)dbContext).ObjectContext;
        ObjectStateManager objectStateManager = ctx.ObjectStateManager;
        var l1 = objectStateManager.GetObjectStateEntries(EntityState.Added);
        var l2 = objectStateManager.GetObjectStateEntries(EntityState.Modified);
        var l3 = objectStateManager.GetObjectStateEntries(EntityState.Deleted);
        //var l4 = objectStateManager.GetObjectStateEntries(EntityState.Detached);
        var l5 = objectStateManager.GetObjectStateEntries(EntityState.Unchanged);

        var existingProductInBasket = dbContext.BasketProducts.AsNoTracking().SingleOrDefault(b => b.BasketId == product.BasketId && b.ProductId == product.ProductId);
        var l6 = objectStateManager.GetObjectStateEntries(EntityState.Added);
        var l7 = objectStateManager.GetObjectStateEntries(EntityState.Modified);
        var l8 = objectStateManager.GetObjectStateEntries(EntityState.Deleted);
        //var l4 = objectStateManager.GetObjectStateEntries(EntityState.Detached);
        var l9 = objectStateManager.GetObjectStateEntries(EntityState.Unchanged);

        //objectStateManager.
        dbContext.Entry<BasketProduct>(product).State = existingProductInBasket == null ? EntityState.Added : EntityState.Modified;

    }
4

2 回答 2

1

当您使用 asNoTracking() 时,您会得到一个无法使用 EntityState.Modified 正常更新的未连接实体。然后,一个技巧是用非缓存的实体值替换缓存的实体值。

这是我在需要 asNoTracking 的特殊情况下使用的源代码。有可能

private T ReplaceEntity(T cachedEntity, T nonCachedEntity) {

     dbContext.Entry(cachedEntity).CurrentValues.SetValues(nonCachedEntity);

     return cachedEntity;
}

一个常见的用途可以是:

public virtual T FindFirstBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate, bool asNoTracking = false)
{
     if (asNoTracking)
     {
          T cachedEntity = dbContext.Set<T>().FirstOrDefault(predicate);
          T nonCachedEntity = dbContext.Set<T>().AsNoTracking().FirstOrDefault(predicate);

          return ReplaceEntity(cachedEntity, nonCachedEntity);
     }
     return dbContext.Set<T>().FirstOrDefault(predicate);
}

对于您的情况:

var cachedEntity = dbContext.BasketProducts.SingleOrDefault(b => b.BasketId == product.BasketId && b.ProductId == product.ProductId);
var nonCachedEntity = dbContext.BasketProducts.AsNoTracking().SingleOrDefault(b => b.BasketId == product.BasketId && b.ProductId == product.ProductId);

var product= ReplaceEntity(cachedEntity, nonCachedEntity);
dbContext.Entry<BasketProduct>(product).State = EntityState.Modified;

希望能帮助到你!!

于 2014-03-28T19:59:30.303 回答
0

那实际上是坏事。从概念上讲,要习惯 EF 如何附加和跟踪事物的想法可能有点困难。秘诀是要记住,如果您有一个对象图(与其他对象有关系的对象),只要该图的一个对象与状态 X 相连,那么图中的所有其他对象似乎也都处于该状态。

在我的场景中,我非常愚蠢地使用 var bpro = new BasketProduct(ba, ba.BasketProducts.First().Product, 3); 创建一个实际已经存在于数据库中的测试产品,它是包含篮子及其产品的对象图的一部分。当我尝试附加这个“新”篮子时,EF 正确地抱怨附加图中已经存在具有相同键的对象!

于 2012-12-04T17:49:04.120 回答