none
How do I delete a record with Entity Framework 5 RRS feed

  • Question

  • I upgrade my code from .Net 4 to .Net 4.5. Now the DeleteObject and commandtimeout no longer compiles

    How do I delete a record with Entity Framework 5

    • Moved by Bob Wu-MTModerator Monday, September 10, 2012 2:54 AM (From:Windows Forms Data Controls and Databinding)
    Friday, September 7, 2012 12:37 PM

Answers

  • Hi Arne,

    The DeleteObject method exists, but is on the ObjectContext API not DbContext. If you have updated your models to use DbContext and DbSet then the way to delete a record is just to remove the entity from the DbSet collection and call SaveChanges on the Context.

    You could also manually set the state of the object to Deleted via the entry method. Something like:

    context.Entry(object).State = EntityState.Deleted

    It depends which works best for your scenario. You may need to set child items to deleted as well if you use the EntityState method.


    We are seeing a lot of great Entity Framework questions (and answers) from the community on Stack Overflow. As a result, our team is going to spend more time reading and answering questions posted on Stack Overflow. We would encourage you to post questions on Stack Overflow using the entity-framework tag. We will also continue to monitor the Entity Framework forum.

    • Marked as answer by Arne MN Tuesday, September 11, 2012 5:52 PM
    Monday, September 10, 2012 4:30 PM
    Moderator

All replies

  • Hi Arne,

    According to your description, this issue is about Entity Framework, I will move it to ADO.NET Entity Framework and LINQ to Entities forum for better support.

    Best Regards,


    Bob Wu [MSFT]
    MSDN Community Support | Feedback to us

    Monday, September 10, 2012 2:53 AM
    Moderator
  • Hi Arne,

    The DeleteObject method exists, but is on the ObjectContext API not DbContext. If you have updated your models to use DbContext and DbSet then the way to delete a record is just to remove the entity from the DbSet collection and call SaveChanges on the Context.

    You could also manually set the state of the object to Deleted via the entry method. Something like:

    context.Entry(object).State = EntityState.Deleted

    It depends which works best for your scenario. You may need to set child items to deleted as well if you use the EntityState method.


    We are seeing a lot of great Entity Framework questions (and answers) from the community on Stack Overflow. As a result, our team is going to spend more time reading and answering questions posted on Stack Overflow. We would encourage you to post questions on Stack Overflow using the entity-framework tag. We will also continue to monitor the Entity Framework forum.

    • Marked as answer by Arne MN Tuesday, September 11, 2012 5:52 PM
    Monday, September 10, 2012 4:30 PM
    Moderator