Deleting an item with entity framework

前端 未结 2 1254
萌比男神i
萌比男神i 2021-02-18 23:58

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 m

2条回答
  •  猫巷女王i
    2021-02-19 00:08

    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();  
     }  
    

提交回复
热议问题