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
        //mark it as deleted
        context.ObjectStateManager.ChangeObjectState(car, EntityState.Deleted);
        //save changed - effectively saying delete the entity with this ID

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
        //mark it as deleted
        context.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Deleted);
        //save changed - effectively saying delete the entity with this ID

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


  1. Awesome, thanks for the tip!

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

  3. Cool. this helped

  4. ta, this helped.

  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.

  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

  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

  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.

  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.

  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

  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

  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

  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

  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

  15. OFF PAGE
    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.
    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!!
    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.
    Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. 
    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.
    xtremely pleasant article, I appreciated perusing your post, exceptionally decent share, I need to twit this to my adherents. Much appreciated!.
    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. 
    I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up.
    Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.
    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.

    software company

  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

  17. It’s wonderful to hear from you,Thank you for sharing your post

  18. Visit ( http://BUYONLINEDOCUMENTS.COM/ ).. ( ).. WhatsApp ,Call Or TEXT … +1 (725 222 8302) Buy Registered Real Passport Legally, Driver License , ID CARD, Social Security , SSN, SSC. Birth Certificate, Death Certificate, Divorce Papers, Resident Permit, Work Permit, Military Card, Green Card, Degree, Diploma, IELTS, TOEFL , International Cards , Custom Certificates , etc. FOR ALL COUNTRIES, STATES CITIES , UNIVERSITIES ( ).. WhatsApp ,Call Or TEXT.. +1 (725 222 8302)

    Visit ( http://BUYONLINEDOCUMENTS.COM/ ).

    Buy Passport online, passport for sale online, Diplomatic passport, Registered Passport, Real Passport,
    Buy Driver License online , Driver’s License, Drivers License for sale online, ID Card,Military Card
    Buy Visa Online, Visa for sale , Green card for sale, Resident Permit for sale online
    Buy Ielts online, Buy Diploma for sale online,
    Buy documents online, document online, International Cards,United Nation Passport,UN Passport.
    Buy Social Security Card Online, Social Security Card for sale online, SSN, SSC
    Buy Birth Certificate Online, married certificate,Divorce papers, Utility Bills,

    Visit ( http://BUYONLINEDOCUMENTS.COM/ ).

    We also have fraud Bible over 37gb of files including everything
    Everything on UK including Bank Statements and Utility,
    All Paystub on US, utility etc and lots of Bank Statements,
    Selfie with Passport Pictures lots of them over 6gb,
    Credit card template with over 60 Bank logos and Designs,
    Forensic Softwares, Barcodes, Vertus Fluid Mask etc
    Everything on canada, France, Switzerland,
    Military Id psd ,Flight tickets psd, signatures pics Fonts, Counterfeit Currencies Psd
    Latest Templates Available .. Passport,Driver License,ID Card ,SSN, SSC, Birth Certificate etc
    Latest USA and UK Passport and Drivers License, latest Canada Passport, 2d barcode writer, 1d barcode writer, passport pics and selfie etc.

    Contact Information Below
    Official Website … ( http://BUYONLINEDOCUMENTS.COM/ )
    Contact ….
    Contact … Whatsapp .. +1 (725 222 8302)
    Contact … Call … +1 (725 222 8302)
    Contact… TEXT … +1 (725 222 8302)

  19. 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.

  20. My son would like to play and seek with Miffy

    Ey Yaa

  21. Purchase Real Passports, Drivers License, ID Cards, Residence Permits  
    Buy Registered Passport, Driver's License ( http //:  ) +4915244338254

    We are an agency with over 120 branch offices throughout Europe to the Middle East to Asia, Africa North and South America who have the connections and the ability to issue government registered Identification and travel documents. We issue a range of documents which are all registered in the databases of the authorities in charge of issuing the document for the respective countries. We sell the following; Passports, Driver's License, ID cards, Birth Certificates, Marriage Certificates, Utility bills and so on English language proficiency tests like; IELTS, TOEFL, GRE, GMAT, and many more

    Contact us today to provide you with limitless opportunities. Our contact information is as listed below;

    Email ..  
    Whatsapp ...... +4915244338254
    website .... http //:  
    - Buy Real Registered UK Passport Now

    - Buy Real Registered UK passport online

    - Buy original British passport 24/7 service

    - Purchase Authentic English passport

    - Buy Real original Diplomatic passport Now

    - Buy cheap Registered Diplomatic passport

    - Buy German passport online

    - Buy Real Registered German passport Now

    - Buy Real Registered European passport Today

    - Obtain Real Authentic Passport Online Today

    - Buy Real Registered Italian Passport

    - Buy Real Registered Spanish Passport

    - Buy Real Registered Portuguese Passport

    - Buy Registered Driver's License

    - Buy Driver's License Online

    - Buy Real Registered Driver's License Online

    - Buy Authentic Driver's License; 24/7 service

    - Buy German Driver's License Today

    - Buy Real Registered German Driver's License

    - Buy ID cards in Europe

    - Buy European ID card online

    - Buy Registered Belgian ID card

    - Buy Real Registered Belgian Driver's License

    - Buy driver's license online

    - Buy a Real Driver's License

    - Buy International Driver's License

    - Get Passport, ID Card, Driver's License

    - Buy a Provisional Driver's License

    - Buy Another Driver's License

    - Obtain Driver's License in Florida

    - Buy Driver's License in China

    - Purchase Driver's License in Thailand

    - Buy Driver's License EU

    - Buy Driving License with no exams

    - Buy Legal Driving License for Germany with MPU

     ketiakim@yahoo.comPassport, ID card, Driver's License

    - Buy Malta Passport Now

    - Get Your Citizenship Today at Discount Prices

    - Purchase French Citizenship


    - Buy Real Registered Australian Passport Online

    - Buy Australian Passport, ID Card, Driver's License

    - Buy Government Database Registered Documents almost

    Email ..... whatsapp....+4915244338254 

  22. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also
    Transparent stickers

  23. I am certainly making the most of your site. You unquestionably have some extraordinary knowledge and incredible stories.embossed stickers

  24. Hi! Great work. I feel nice to be here reading your authentic work.
    Custom Sticker

  25. I always appreciate quality content, Thanks to you for sharing such post.
    Ask Questions Get Answers

  26. code as a starting point for your project ... it definitely handles multiple clients. Regarding the message about the 'Task' class ... the 'Task' class is found in the .Net 4.0 product rapid assemblies and should be already referenced from a .Net 4.0 console ap

  27. If you visit other cities and you want to have awesome fun then please meet my friends who are hot and sexy meet these wild beauties for the pleasure you are seeking I assure you that these young women are incredibly sexy and passionate to the degree that you imagine your wildest fantasies will come true hurry up and call them you can know a little about them on this page and then you can choose which one to meet you must grab this opportunity of being with a fine woman with delicate features and romance them so that your life is cherished forever you can go to these towns to have these beauties Watch Series with you and enjoy your life to the fullest just go and book a hotel and then invite these girls to your room for some adventure.

  28. OGEN Infosystem provides professional website designing services in delhi, India. We have a great team of experienced developers and designers and we also provide SEO Services.
    SEO Service in Delhi

  29. Free Web Directory is an online catalog of websites arrange by categories. Highly specialized SEO friendly human edited free web directory. Submit your websites free with deeplinks. Free Web Directory

  30. Links Catalog – Premium Link Directory Features high quality and well-designed websites curated by human editors and organized by category. Website Premium Link Directory listings for businesses, companies, products, and services organized in relevant categories. Links Catalog increase your domain authority for a higher rank on search engines.

  31. The latest Greece Powerball Results. We publish results of the Greece Powerball 

    South Africa's premier online and mobile sports betting site. You'll have immediate access to the thrilling world of sports betting anywhere and Greece Powerball .

  32. This particular is usually apparently essential and moreover outstanding truth along with for sure fair-minded and moreover admittedly useful My business is looking to find in advance designed for this specific useful stuffs… writing & marketing

  33. Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards, rijschool geleen

  34. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! sexy ondermode

  35. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. logo firmy

  36. What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much. de mulder venray

  37. Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. architectenbureau eindhoven

  38. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: blog o grafice

  39. I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day! architectenbureau nijmegen

  40. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. constructiewerk

  41. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. e liquid millers

  42. Thank you for taking the time to publish this information very useful! glazen schuifwanden

  43. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. schoonmaakbedrijf eindhoven

  44. custom CBD oil boxes are printed packaging for your products. custom CBD oil packaging is designed with logo and your specification. custom CBD oil packaging boxes are available at wholesale rates. custom CBD oil box packaging is inspiring packaging solution for your product. Get custom printed CBD oil boxes at wholesale rate with free shipping cost all across the United States and Canada.

  45. s the population of the world is increasing also there increasing the population of food lovers increasing. There are many peoples who are just mad to eat food.All the time they wonder to search for the taste. After eating the tasty food they also want to bring for their families. That purpose packaging comes. packaging id must be that kind which can secure the food and also keep in its original taste. So Many companies doing their best for packaging of the products.iCustomBoxes have the solution to that problem. They make every kind of food boxes like Chinese noodle boxes,donut packaging and candy boxes with windows etc.
    \Cardboard Cigarette boxes
    Custom Lip balm boxes
    Cardboard box with handle

  46. Fine information, many thanks to the author. It is puzzling to me now, but in general, the usefulness and importance is overwhelming. Very much thanks again and best of luck!
    Custom Packaging Boxes
    new birthday wishes

  47. Chat with millions of new friends on QQ, now with HD video calls and live translation to 50 idioms. Massive chat rooms and users from all around the world. QQ Online

  48. buy targeted traffic for ecommerce or affiliate website. Best place to buy real human targeted traffic. 100% Guaranteed Real Targeted Visitors. ➤Targeted traffic that converts. Buy website traffic, buy targeted traffic and increase web site traffic.

  49. Our tutors focus on providing step-by-step solutions to every assignment problem or focus on each topic of assignment help online.

  50. Buy Packaging Boxes has opened new avenues for custom packaging boxes. Our all color digital and offset printing services allow you to have excellent quality personalized packaging.

    Hemp Oil Boxes

    Beard Oil Boxes

    Medicine Boxes

    Packaging Boxes Products


  51. Buy WEED Online UK

    ONLINE WEED SHOP#1 online dispensary. Shop and buy weed online including all types of cannabis, edibles, vapes, shatter, wax and concentrates and more.

    Get Visit Here for More Information:- buy weed online UK
    We are always open and ready to serve you 24 hours a day and seven days a week. Do not hesitate to call or text us at any given time should you need help.

  52. Very well written information. It will be valuable to everyone who utilizes it, Keep up the good work I will definitely read more posts. Thank you for sharing this with us.
    Database Homework Help
    Programming Assignment Help

  53. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Thanks for sharing the information keep updating, looking forward to more posts.
    High Quality Product Images

    Custom Business Cards

  55. I like the valuable info in your articles. I’ll bookmark your blog and check again here regularly. I” ll learn plenty of new stuff right here! Best of luck for the next!
    Custom Boxes with logo

  56. Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info. Fantastic nice. I appreciate this post. and thank you for sharing an amazing article...
    Custom Packaging Boxes

  57. i am browsing this website dailly and get nice facts from here all the time

  58. I really thank you for the valuable info on this great subject and look forward to more great posts
    Custom Boxes UK

  59. Thanks for sharing such great information, I highly appreciate your hard-working skills as the post you published have some great information which is quite beneficial for me, I hope you will post more like that in the future.
    Custom Packaging Boxes

  60. I am very enjoyed for this blog. Its an informative topic. It helps me very much to solve some problems. Its opportunity are so fantastic and working style so speedy.
    Printed Labels
    Custom Stickers UK
    London Instant Printing

  61. This comment has been removed by the author.