Search code examples
c#linq-to-sqldelete-row

Linq to SQL delete a record from database taken from another context


The following code:

var record = GetDatabaseRecordByID(UniqueObjectID);

if (record != null)
{
    using (var db = new DBContext())
    {
        db.GetTable(typeof(T2)).DeleteOnSubmit(record);
        db.SubmitChanges();
    }
}

Throws this error:

Cannot remove an entity that has not been attached.

This error returns, because GetDatabaseRecordByID() retrieves the record from a different DBContext.

The code has turned out this way over time due to some difficult refactoring required from some equally difficult caching bugs. I can create a new override method for GetDatabaseRecordByID(DBContext... ) but would prefer to avoid this if possible.

Is it at all possible to delete a record from a different context? I am assuming the answer is no.


Solution

  • Ended up doing a fairly big refactor, I think the answer to this question is no it's not possible.