C# 使用实体框架删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15227339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:32:54  来源:igfitidea点击:

Deleting an item with entity framework

c#linqentity-framework

提问by aleczandru

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 DeleteObjectmethod on the context. I tried doing that but it seems I have no DeleteObjectmethods.

我正在尝试使用 Entity Framework 删除一个对象,在互联网上的所有教程中,我发现为了做到这一点,您必须DeleteObject在上下文中调用该方法。我尝试这样做,但似乎我没有DeleteObject方法。

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?)

“DataAccess.Models.BooksEntities”不包含“DeleteObject”的定义,并且找不到接受“DataAccess.Models.BooksEntities”类型的第一个参数的扩展方法“DeleteObject”(您是否缺少 using 指令或程序集引用?)

What am I doing wrong?

我究竟做错了什么?

采纳答案by Mark Oreta

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

您使用的是 DbContext 还是 ObjectContext?如果您有 DbContext,则需要使用Remove函数:

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

回答by premkumar

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.

DbContext 具有称为 Entry 和 Entry 的方法,这些方法获取给定实体的 DbEntityEntry 并提供对有关实体的信息的访问,并返回能够对实体执行操作的 DbEntityEntry 对象。现在我们可以通过将实体状态更改为 EntityState.Deleted 来对上下文执行删除操作。

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