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();
评论
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.
Attach
? Why not justRemove
andSaveChanges
?