I’ve been trying to figure out a good solution to this for most of the afternoon, but to no avail.
When I query data using the entity framework (EF), I always use MergeOption.NoTracking as I don’t want to use database objects for display in my views. I end up taking the POCO classes generated by the EF and mapping them into view models which have cute little attributes such as required, display name, etc. When I need to make updates, I end up mapping my view models back into the classes generated by the entity framework and perform the create or update action.
I’m trying to find an easy way to delete a relationship with my objects, but since they are detached, I haven’t been able to find a way to do it. I saw someone recommend attaching and removing the object, but since my object is detached that won’t work (it results in an exception with the message Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached.).
Here is an example of my current code:
//Find the records that need to be deleted.
var productVersionsToDelete = (from pv in existingDownloadFile.ProductVersions
where !selectedVersions.Contains(pv.Id)
select pv).ToList();
foreach (var productVersionToDelete in productVersionsToDelete) {
existingDownloadFile.ProductVersions.Attach(productVersionToDelete);
existingDownloadFile.ProductVersions.Remove(productVersionToDelete);
}
Does anyone have recommendations for deleting objects from a detached state?
The problem is, once attach is called, the whole object graph is attached. Given a
DbContextcalledcontext, an example which should work would be the following:This assumes
DownloadFilesis the name of a property on yourDbContextwhich exposes entities which match the type ofexistingDownloadFile.The exception you were getting is because once you attach a
ProductVersion, it attaches the relatedexistingDownloadFile, which can only be attached once.