The project uses the version 6.1.3.

In different sources I have seen different ways to delete a record from the database:

  1. Mark object as deleted: _context.Entry(obj).State = EntityState.Deleted;
  2. Use the Remove() method: _context.Set<T>().Remove(obj);

In both cases, the deletion will occur the next time you call the SaveChanges() method.

I tried to find out the differences between these methods: I could not find anything intelligible.

Tell me in what cases it is customary to use one or another method, maybe there are some nuances / recommendations?

    1 answer 1

    The Remove method checks the status of an entity before deletion and does not allow deleting entities that are not attached to the context:

     var foo = new Foo(); _context.Entry(obj).State = EntityState.Deleted; // даст непонятный DbUpdateException при сохранении изменений _context.Set<T>().Remove(foo); // даст InvalidOperationException сразу 

    On the other hand, explicit assignment of status can help when you need to delete an entry by key:

     var foo = new Foo { Id = 1 }; _context.Entry(obj).State = EntityState.Deleted; // удалит запись номер 1 _context.Set<T>().Remove(foo); // все еще InvalidOperationException 
    • those. method number one will be faster , the only thing to remember about related entities, i.e. they must be loaded for correct deletion, otherwise we catch an exception, right? - Bald
    • @Bald very slightly. If it comes to accelerating EF, you need to start by disabling the autodetection of changes - and not by removing the security checks. - Pavel Mayorov
    • @Bald about related entities - did not understand. But the situation with them in both ways of working is no different. - Pavel Mayorov
    • for example, public class RequestHistory { public int Id {get;set;} public int RequestId {get;set; }} public class RequestHistory { public int Id {get;set;} public int RequestId {get;set; }} in this case, the deletion will not occur if the RequestId property is not filled - Bald
    • @Bald why? - Pavel Mayorov