开发者

How Can I Detect If An Entity Is Already Attached Using Stub Entities

开发者 https://www.devze.com 2022-12-10 02:23 出处:网络
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 at

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号