Delete a record with the primary key

David Thielen 2,231 Reputation points
2023-06-05T20:32:22.7166667+00:00

Hi;

Is there a way to delete a record by its primary key?

Yes I know I can do the following:

using (var context = new MyDbContext())
{
    var entity = context.MyEntity.Find(id);
    context.MyEntity.Remove(entity);
    context.SaveChanges();
}

But I prefer to not incur the unnecessary overhead of loading the record first.

I am aware of this question but it is 11 years old and I'm hoping there's been a solution for this added since then.

thanks - dave

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
694 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,281 Reputation points Microsoft Vendor
    2023-06-06T03:51:58.9166667+00:00

    @David Thielen, Welcome to Microsoft Q&A, If you want to delete a record based on the primary key and don't want to spend unnecessary overhead for it, I recommend that you use SQL RAW method to delete the record, like the following:

    using (var context = new YourDbContext())
    {
        var sql = "DELETE FROM YourTable WHERE Id = {0}";
        context.Database.ExecuteSqlRaw(sql, yourEntityId);
    }
    
    

    The above code delete the records in the sql server without loading the entity type.

    Best Regards,

    Jack

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.  


0 additional answers

Sort by: Most helpful