The normal pattern I use when deleting by ID is this:
new Repository().DeleteByID(id);
class Repository{
Repository(){
this.Context = new Context();
}
GetByID(id){
return (from x in this.Context.Entities
where x.ID == id select x).FirstOrDefault();
}
DeleteByID(id){
Entity e = new Repository().GetByID(id);
Delete(e);
}
Delete(Entity e){
e.MarkAsDeleted();
this.Context.Entities.ApplyChanges(e);
this.Context.SaveChanges();
e.AcceptChanges();
}
I fetch the entity with a fresh context to be able to ApplyChanges as I normally work with self-tracking entities (as described by the answer in this thread: http://social.msdn.microsoft.com/Forums ... 2d3490f190). I know that I could just working "attached" and delete the object from the context in this case, but this would not match with how we normally delete objects (see Delete method).
This works perfectly, but I have now found myself in a more complicated situation that I will not try to simplify and explain.
In this situation, I would like to fetch the object that is to be deleted and also fetch related entities before deletion.
If I change the DeleteByID-method to this ...
DeleteByID(id){
Entity e = new Repository().GetByID(id);
e.RelatedEntity = new RelatedEntityRepository().GetByID(e.RelatedEntityID);
Delete(e);
}
Delete(Entity e){
e.MarkAsDeleted();
e.RelatedEntity.MarkAsDeleted();
this.Context.Entities.ApplyChanges(e);
this.Context.SaveChanges();
e.AcceptChanges();
e.RelatedEntity.AcceptChanges();
}
... something goes wrong and I get a foreign key exception, probably because the related entities are not deleted properly, but why???
The code works fine if I do not fetch things by using two querys but instead fetch the entity and its related object in the same query (which I do not want to do in this situation) like this ...
GetByID(id){
return (from x in this.Context.Entities
.Include("RelatedEntity")
where x.ID == id select x).FirstOrDefault();
}
... which boggles me completely.
Can someone shed any light on this situation?