0

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();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jake12342134
  • 1,539
  • 1
  • 18
  • 45

1 Answers1

0

You can use:

_configDbContext.Database.ExecuteSqlCommand

or try

_configDbContext.PolicySets.RemoveRange

You can inspire also from this article Entity Framework. Delete all rows in table

D A
  • 1,724
  • 1
  • 8
  • 19
  • The issue isn't removing them, it's getting them to attach to the context. – Jake12342134 Jul 03 '20 at 14:08
  • Why do you need them to attach to context if in the end you need them deleted? – D A Jul 03 '20 at 14:11
  • I just need to delete the entries from the db. The answer in the link I posted says that you need to attach them first before deleting them. – Jake12342134 Jul 03 '20 at 14:30
  • Attach, let context, to keep track of object and it's references in else where, when we use the `AsNoTracking()`, and that method, cause the Context to do not lookup data in memory storage *of context*, and also do not load new data into the memory *of context* too, but I'm not sure if it really is required to attach them before delete or not. maybe Context automatically lookup for them with ID and remove them if any attached environment exists. also in MVC we mostly use scoped injection, or new in Controller, which cause every new request generate new Context and a new allocated Memory in RAM – Hassan Faghihi Dec 01 '20 at 06:24