How to delete an object by id with entity framework

后端 未结 9 1878
你的背包
你的背包 2020-11-29 04:05

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         


        
9条回答
  •  春和景丽
    2020-11-29 04:46

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

        using (var _context = new DBContext(new DbContextOptions()))
        {
            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;
                }
            }
        }
    

    This way, it will query the database twice only if an exception occurs when trying to remove the item with the specified ID. Then if the item is not found, it returns a meaningful message; otherwise, it just throws the exception back (you can handle this in a way more fit to your case using different catch blocks for different exception types, add more custom checks using if blocks etc.).

    [I am using this code in a MVC .Net Core/.Net Core project with Entity Framework Core.]

提交回复
热议问题