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.