How to delete an object by id with entity framework

后端 未结 9 1874
你的背包
你的背包 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: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();
    

提交回复
热议问题