如何通过实体框架的id删除对象 [英] How to delete an object by id with entity framework
本文介绍了如何通过实体框架的id删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var customer = context.Customers.First(c => c.Id = 1);
context.DeleteObject(customer);
context.Savechanges();
所以我需要打两次数据库。有一个更简单的方法吗?
解决方案
与@Nix相同的一个小变化是强类型:
如果你不想查询它只是创建一个实体,然后删除它。
Customer customer = new Customer(){Id = id};
context.Customers.Attach(customer);
context.Customers.DeleteObject(customer);
context.SaveChanges();
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);
context.DeleteObject(customer);
context.Savechanges();
So I need to hit database twice. Is there a easier way?
解决方案
The same as @Nix with a small change to be strongly typed:
If you don't want to query for it just create an entity, and then delete it.
Customer customer = new Customer () { Id = id };
context.Customers.Attach(customer);
context.Customers.DeleteObject(customer);
context.SaveChanges();
这篇关于如何通过实体框架的id删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文