21

I am trying to delete an object using Entity Framework and on all the tutorials on the internet I found that in order to do that you have to call the DeleteObject method on the context. I tried doing that but it seems I have no DeleteObject methods.

Here is my code:

public void DeleteBook(int bookId)
    {
        Book book = (Book)bookContext.Books.Where(b => b.Id == bookId).First();
        bookContext.DeleteObject(book);
    }

This is the error I get:

'DataAccess.Models.BooksEntities' does not contain a definition for 'DeleteObject' and no extension method 'DeleteObject' accepting a first argument of type 'DataAccess.Models.BooksEntities' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

1
  • 2
    If you take the (Book) cast off the Book assignment, change the Book variable to var, what type is shown when hovered over? I think you're using the wrong class. Commented Mar 5, 2013 at 15:18

2 Answers 2

37

Are you using a DbContext or an ObjectContext? If you have a DbContext you need to use the Remove function:

public void DeleteBook(int bookId)
    {
        Book book = (Book)bookContext.Books.Where(b => b.Id == bookId).First();
        bookContext.Books.Remove(book);
    }
2
  • 10
    You need to add save changes.
    – Netferret
    Commented Dec 2, 2016 at 10:36
  • You need to save changes: bookContext.SaveChanges()
    – user14608136
    Commented Apr 18, 2021 at 17:08
8

The probable solutions of deleting the entity without retrieving it By Changing State

DbContext has methods called Entry and Entry, these methods get a DbEntityEntry for the given entity and provide access to the information about the entity and return a DbEntityEntry object able to perform the action on the entity. Now we can perform the delete operation on the context by just changing the entity state to EntityState.Deleted.

 using (Entities Context = new Entities())  
 {  
    Book  deptBook  = new Book  { Id  = bookId };  
    Context.Entry(deptBook).State = EntityState.Deleted;  
    Context.SaveChanges();  
 }  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.