How to delete an object by id with entity framework

后端 未结 9 1854
你的背包
你的背包 2020-11-29 04:05

It seems to me that I have to retrieve an object before I delete it with entity framework like below

var customer = context.Customers.First(c => c.Id == 1         


        
相关标签:
9条回答
  • 2020-11-29 05:02

    In Entity Framework 6 the delete action is Remove. Here is an example

    Customer customer = new Customer () { Id = id };
    context.Customers.Attach(customer);
    context.Customers.Remove(customer);
    context.SaveChanges();
    
    0 讨论(0)
  • 2020-11-29 05:05

    A smaller version (when compared to previous ones):

    var customer = context.Find(id);
    context.Delete(customer);
    context.SaveChanges();
    
    0 讨论(0)
  • 2020-11-29 05:05

    This answer is actually taken from Scott Allen's course titled ASP.NET MVC 5 Fundamentals. I thought I'd share because I think it is slightly simpler and more intuitive than any of the answers here already. Also note according to Scott Allen and other trainings I've done, find method is an optimized way to retrieve a resource from database that can use caching if it already has been retrieved. In this code, collection refers to a DBSet of objects. Object can be any generic object type.

            var object = context.collection.Find(id);  
            context.collection.Remove(object);
            context.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题