find a location for property in a new city

Monday, 28 March 2011

How to delete an entity by ID in Entity Framework

It may seem unnatural to delete Entities in Entity Framework. In the days of stored procedures I used to just pass an ID where as now you need to get the entity before deleting it. It seems inefficient - you're basically making two database hits when surely you can do it in one database call, right? Well it is difficult but entirely possible.

Since you do not have the entity you will need you will effectively be updating a detached entity which is a technique in itself. The trick here is that we are making a fake entity that shares the Entity Key (EF version of a primary key) with the one that needs deleting. Then we mark it as deleted and SaveChanges.

public void DeleteByID(object id)
{
    //make fake entity and set the ID to the id passed in
    var car = new Car();
    car.ID = id;

    using (var context = new MyDataContext())
    {
        //add this entity to object set
        context.CreateObjectSet<Car>().Attach(car);
        //mark it as deleted
        context.ObjectStateManager.ChangeObjectState(car, EntityState.Deleted);
        //save changed - effectively saying delete the entity with this ID
        context.SaveChanges();
    }
}

It is worth noting that I am following my own twist on the Repository pattern for data access so I have an "EntityRepository" that manages everything EF related. This is where I will make my generic "DeleteByID" method. My EntityRepository uses generics to specify the type of entities that are dealt with so this has to be completely reusable by any entity set (TEntity) or object context (TContext).

How to Delete by ID in a generic way

public void DeleteByID(object id)
{
    var item = new TEntity();
    var itemType = item.GetType();

    using (var context = new TContext())
    {
        //get the entity container - e.g. MyDataContext - this will have details of all its entities
        var entityContainer = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
        //get the name of the entity set that the type T belongs to - e.g. "Cars"
        var entitySetName = entityContainer.BaseEntitySets.First(b => b.ElementType.Name == itemType.Name).Name;
        //finding the entity key of this entity - e.g. Car.ID
        var primaryKey = context.CreateEntityKey(entitySetName, item).EntityKeyValues[0];
        //using Reflection to get and then set the property that acts as the entity's key
        itemType.GetProperty(primaryKey.Key).SetValue(item, id, null);
        //add this entity to object set
        context.CreateObjectSet<TEntity>().Attach(item);
        //mark it as deleted
        context.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Deleted);
        //save changed - effectively saying delete the entity with this ID
        context.SaveChanges();
    }
}

These both translate to the following SQL:
delete from [dbo].[Cars]
where  ([ID] = 123)
And there it is - a reusable delete by ID function with no SELECT!

Follow britishdev on Twitter

19 comments:

  1. Awesome, thanks for the tip!

    ReplyDelete
  2. Thank you for the tip. You have a great blog!

    ReplyDelete
  3. Cool. this helped

    ReplyDelete
  4. ta, this helped.

    ReplyDelete
  5. In exchange for full restitution of the embezzled funds, we agreed not a prosecute. Both the police and district attorney encouraged this course of action.
    http://foxempiretv.com/wp-content/plugins/zingiri-forum/mybb/showthread.php?tid=367687

    ReplyDelete
  6. in exchange for full restitution of the embezzled funds, we agreed not a prosecute. Both the police and district attorney encouraged this course of action.fake id

    ReplyDelete
  7. Queries play key roles to access the target so do not shy to ask questions. Usually, people do not remember the ID name as it is a fake name on ID. So you can ask common questions related to ID. If you get an unsatisfied response then ask the question in a different way to get the response fake id

    ReplyDelete
  8. Motifz Designer Lawn. 1, 2 & 3 Piece Unstitched Premium Embroidered Lawn 2019, Premium embroidered Lawn, Premium lawn, Premium lawn 2019, Motifz, Premium lawn in Pakistan, Summer collection. Shipping worldwide. Stitching option available.

    ReplyDelete
  9. I'm really impressed about the info you provide in your articles. If you want to invest in suits and be stress-free, then you should shake hands with us. We are providing great clothing in the most reasonable price range that you wouldn’t find anywhere else. Put your trust in us as your supplier since we are the prominent custom stickers printing You can rely on us for the clothing problems we assure you we will never let our customers down.

    ReplyDelete
  10. Attractive information on your blog, thank you for taking the time and share with us.
    Die Cut Bookmarks
    Reflective Stickers
    custom stickers uk
    Custom Box Printing

    ReplyDelete
  11. Wow, excellent post. I'd like to draft like this too - taking time and real hard work to make a great article. This post has encouraged me to write some posts that I am going to write soon
    custom wig pillow boxes
    custom hair extension boxes
    custom burger boxes

    ReplyDelete
  12. Hello, I want to subscribe for this web site to take most up-to-date updates, thus where can i do it please help out.
    Custom Packaging Boxes
    Custom Printed Boxes Uk
    Logo Stickers

    ReplyDelete
  13. Present your products in the best quality custom printed boxes. Custom boxes make it easy to design and create beautiful custom printed boxes UK. Are you looking for Buy Packaging Boxes with Custom Packaging Boxes at wholesale prices? We offer a huge variety of custom packaging boxes at your doorstep with free shipping.
    Custom Boxes

    ReplyDelete
  14. StickerZone is the fastest and easiest way to buy custom sticker printing. Order in 60 seconds and we’ll turn your designs and illustrations into custom stickers UK, custom labels, window, magnets, buttons and packaging in days. We offer free online proofs, free worldwide shipping and super fast turnaround. We don’t just custom stickers printing. StickerZone provide a wide variety of custom signage for all business types.
    Custom Sticker Printing

    ReplyDelete
  15. OFF PAGE
    I create a cheap rete off page seo WOW, WHAT A EXCELLENT POST. I REALLY FOUND THIS TO MUCH INFORMATICS. IT IS WHAT I WAS SEARCHING FOR.I WOULD LIKE TO SUGGEST YOU THAT PLEASE KEEP SHARING SUCH TYPE OF INFO.THANKS
    SEO LINKBUILDING
    I I create a cheap rete seo link building reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up.
    BACKLINKS
    I create a cheap rete backlinks seo Megan this is a great way to organize them all!! I have tried to hand write them, but I always forget when they are or what I have linked up. Thank you very much for sharing this with us at TaDa Thursday!!
    NICHE COMMENTS
    here is my great offer i will provide you 80 niche relevant hight quality blog comments with high authorize sites good for your website rank your site on google, bing, yahoo etc. All comments are manually No software use.
    SOCIAL BOOKMARKING
    Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. 
    WEB2.0
    here is my great offer i will provide you 80 niche relevant hight quality blog comments with high authorize sites good for your website rank your site on google, bing, yahoo etc. All comments are manually No software use.
    WEB2.0 PROFILES
    xtremely pleasant article, I appreciated perusing your post, exceptionally decent share, I need to twit this to my adherents. Much appreciated!.
    SOCIAL MEDIA SERVICE
    We are truly thankful for your blog entry. You will discover a great deal of methodologies in the wake of going to your post. I was precisely scanning for. A debt of gratitude is in order for such post and please keep it up. 
    BLOG COMMENTING SERVICE
    I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up.
    BLOG COMMENTING PACKAGES
    Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.
    HIGH AUTHORITY BACKLINKS
    I am getting this error message in the Promoted Link Tiles itself. In the left navigation its working though. Also I am able to verify the address while adding it in the promoted links.
    HIGH AUTHORITY BACKLINKS


    software company

    ReplyDelete
  16. Just admiring your work and wondering how you managed this blog so well. It’s so remarkable that I can't afford to not go through this valuable information whenever I surf the internet! Mega Millions Payout

    ReplyDelete