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;
}