How to delete an object by id with entity framework

How to delete an object by id with entity framework

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?

 

 

回答1

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

评论

Why Attach? Why not just Remove and SaveChanges?
– runeks
Sep 25, 2018 at 12:45
 
You have to attach your entity in the context because if you don't do that, you will receive an error while removing. EF can remove entities in this context only Jan 9, 2019 at 14:43
 
@runeks according to the manual the entity must exist in the context before the Remove operation can be performed. See here docs.microsoft.com/en-us/dotnet/api/…
– dwkd
Jan 28, 2019 at 23:51

 

回答2

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

 

回答3

Similar question here.

With Entity Framework there is EntityFramework-Plus (extensions library).
Available on NuGet. Then you can write something like:

// DELETE all users which has been inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
     .Delete();

It is also useful for bulk deletes.

 

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-15 专科是文科,是否可以报考理科的本科
2021-09-15 一网通办 下载发票
2017-09-15 asp.net的临时文件夹
2017-09-15 Cms WebSite 编译非常慢
2015-09-15 access to modified closure 闭包的问题
2015-09-15 错误信息:A TCP error (10013: 以一种访问权限不允许的方式做了一个访问套接字的尝试。) occurred while listening on IP Endpoint=192.168.1.18:8002.
2015-09-15 如何kill掉TaobaoProtect.exe
点击右上角即可分享
微信分享提示