views:

50

answers:

1

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 = product;
+1  A: 

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.

Craig Stuntz
I would like to mark this as the answer to my question but I have no idea what you are suggesting. Sorry to be so stupid!
DaveB
I added a code example.
Craig Stuntz