How to delete an object by identifier with entity

It seems to me that I need to get an object before I delete it with an entity, as shown below

var customer = context.Customers.First(c => c.Id == 1); context.DeleteObject(customer); context.Savechanges(); 

So I need to hit the database twice. Is there an easier way?

+83
entity entity-framework
Mar 18 '10 at 16:11
source share
8 answers

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

 Customer customer = new Customer () { Id = id }; context.Customers.Attach(customer); context.Customers.Remove(customer); context.SaveChanges(); 
+69
Jan 20 '15 at 16:33
source share

Same as @Nix with a small change that needs to be strictly typed:

If you do not want to request it, just create an object and then delete it.

  Customer customer = new Customer () { Id = id }; context.Customers.Attach(customer); context.Customers.DeleteObject(customer); context.SaveChanges(); 
+51
Dec 09
source share

A similar question is here .

Entity Framework has EntityFramework-Plus (extension 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 deletions.

+23
Jul 23 '13 at 7:11
source share

If you do not want to request it, just create an object and then delete it.

 Customer customer = new Customer() { Id = 1 } ; context.AttachTo("Customers", customer); context.DeleteObject(customer); context.Savechanges(); 
+22
Mar 25 '10 at 1:16
source share

I am using the following code in one of my projects:

  using (var _context = new DBContext(new DbContextOptions<DBContext>())) { try { _context.MyItems.Remove(new MyItem() { MyItemId = id }); await _context.SaveChangesAsync(); } catch (Exception ex) { if (!_context.MyItems.Any(i => i.MyItemId == id)) { return NotFound(); } else { throw ex; } } } 

Thus, it queries the database twice only if an exception occurs when trying to delete an item with the specified ID. Then, if the item is not found, it returns a meaningful message; otherwise, it simply throws an exception (you can handle this by using different catch blocks for different types of exceptions more appropriate for your case, add additional user checks using blocks, etc.).

[I use this code in an MVC.Net Core / .Net Core project with an Entity Framework core.]

+5
Jun 24 '17 at 14:34
source share

Raw sql query is the fastest way, I suppose

 public void DeleteCustomer(int id) { using (var context = new Context()) { const string query = "DELETE FROM [dbo].[Customers] WHERE [id]={0}"; var rows = context.Database.ExecuteSqlCommand(query,id); // rows >= 1 - count of deleted rows, // rows = 0 - nothing to delete. } } 
+2
Feb 28 '14 at 9:49
source share

If you are using EF 1.0, this is the most concise way to do this. There may be other ways, but they have more problems than their IMHO.

0
Mar 18 '10 at 16:21
source share

The dwkd answer basically worked for me in the Entity Framework core, except when I saw this exception:

InvalidOperationException: An instance of the Client entity type cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When connecting existing objects, make sure that only one instance of the object with the given key value is connected. Consider using DbContextOptionsBuilder.EnableSensitiveDataLogging to see conflicting key values.

To avoid an exception, I updated the code:

 Customer customer = context.Customers.Local.First(c => c.Id == id); if (customer == null) { customer = new Customer () { Id = id }; context.Customers.Attach(customer); } context.Customers.Remove(customer); context.SaveChanges(); 
0
Apr 25 '19 at 15:56
source share



All Articles