I have seen and I am sure used this technique with EF Core to remove a record by creating a stub object to save a trip to the db, but using this method does not ever send a delete to the db. Does anyone know why?
public void DeleteById(int blogPostId)
{
// Does not work
// Use Stub to save extra db trip
/*
var blogPost = new BlogPost { Id = blogPostId };
_context.Entry(blogPost).State = EntityState.Deleted;
_context.BlogPosts.Remove(blogPost);
_context.SaveChanges();
*/
// Works
var blogPost = _context.BlogPosts.Find(blogPostId);
_context.Entry(blogPost).State = EntityState.Deleted;
_context.BlogPosts.Remove(blogPost);
_context.SaveChanges();
}
As an additional question, what is difference between using remove directly on the context or on the DbSet as both work fine?
_context.Remove(blogPost);
_context.BlogPosts.Remove(blogPost);
If I change the code to the below:
public void DeleteById(int blogPostId)
{
// Does not work
// Use Stub to save extra db trip
var blogPost = new BlogPost { Id = blogPostId };
//_context.Entry(blogPost).State = EntityState.Deleted;
_context.BlogPosts.Remove(blogPost);
_context.SaveChanges();
// Works
//var blogPost = _context.BlogPosts.Find(blogPostId);
//_context.Entry(blogPost).State = EntityState.Deleted;
//_context.BlogPosts.Remove(blogPost);
//_context.SaveChanges();
}
I get the error below:
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The instance of entity type 'BlogPost' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.