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.]
demonicdaron Jun 24 '17 at 14:34 2017-06-24 14:34
source share