How Can I Detect If An Entity Is Already Attached Using Stub Entities
I want to use stub entities but it seems I cannot use TryGetObjectStateEntry without the full entity? Is there a way to do this with stub entities or any other way to detect if an entity is already attached? AttachTo will throw a InvalidOperationException if I try to attach the same entity twice. I am trying to save a hit to the database. Here is my code;
// Stub entities don't work with TryGetObjectStateEntry, need a full entity?
// product = new Product { ProductID = item.ProductID };
// Full entity from the DB works fine
product = ctx.Products.First(i => i.ProductID == item.ProductID);
ObjectStateEntry entry = null;
if(!ctx.ObjectStateManager.TryGetObjectStateEntry(product.EntityKey, out entry))
{
ctx.AttachTo("Products", product);
}
newItem.Product = pro开发者_如何学Goduct;
Just set the EntityKey of the Reference instead of using stub entities. That always works, so long as you don't need to dereference the related value. Since you'r using stubs, I guess you don't.
newItem.ProductReference.EntityKey =
new EntityKey("MyEntityContextName.Products", "ProductID", item.ProductID);
Obviously, replace "MyEntityContextName" with the actual name of your context.
精彩评论