I use a repository pattern and to make things centralized I created a IValidate interface that each of my repositories can implement. In that I make entity validations depending on their state. So far so good, until I removed an entity. When I tried to access a property from a removed entity I got an exception, the entity was no longer in context.
Ex:
class A
{
int MyClassBId
B MyClassB
}
If I add or update entity A
I can access A.MyClassB
with no hassle. But if I delete (DbSet.Remove) even before calling SaveChanges (my approach of course calls this Validations before save) the references are null. So if I try to access A.MyClassB
again I get null reference, but the "not lazy-loaded" objects are there. For instance, A.MyClassBId
still has the FK for B
.
I understood that DbSet.Remove only marked the entity for deletion, nothing else. Does it also remove it from context? How can I solve this? Call DbSet.Remove and still maintain the references in the object, at least until SaveChanges is called?
Thanks.
You have to understand that two processes are going on:
DbContext
, maintaining their state as Added
, Modified
, Deleted
or Unchanged
. You can check this with a MyDataContext.Entry(MyEntity).State
call. So what happens when you call the DbSet.Remove method is that the entity will be marked for deletion under the covers and outwardly it will be removed from the ICollection that it belonged too.
If you want to keep track of entities that should be deleted on a SaveChanges
call you will have to define a WillBeDeleted
property on the entity and your code will have to take this property into account when counting active entities, validation, etc. The actual DbSet.Remove
call should then be made just before calling SaveChanges
.
Alternatively, you can use MyDataContext.Configuration.AutoDetectChangesEnabled=False
before initialising the DbContext. Now the Entity that is subjected to the DbSet.Remove
method will not be deleted from its ICollection
in the POCO class, but you have no way of knowing that the entity is meant to be deleted without again tracking this in a property of your own.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.