I have an EF Core database context set up that has a particular set of objects. I want to be able to delete these objects from my database via their Id. However I don't want to query the database and extract these objects as they're quite big and I'm trying to avoid the performance overhead.
Looking at this link it seems like a simple enough procedure. Find your Ids, create temporary objects of the same type and then attach them to the context, then remove them.
However when I do this, I get the following exception.
The instance of entity type 'Type' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
I assume this means that because there is already an instance of the object being tracked, I can't then load a second instance of the object into memory using the same id.
How then can I delete these objects using their Id? Loading the original database objects into memory is completely out of the question.
var policySetIdsToDelete = _configDbContext.PolicySets
.Where(ps => ps.SerialNo == serialNumber.ToUpper())
.OrderByDescending(ps => ps.Created).Skip(5).Select(ps => ps.Id.ToString()).ToList();
foreach (var id in policySetIdsToDelete)
{
var policySet = new PolicySet
{
Id = new Guid(id)
};
_configDbContext.PolicySets.Attach(policySet);
_configDbContext.PolicySets.Remove(policySet);
}
_configDbContext.SaveChanges();