Self-tracking entities - Delete problem

Discussion of open issues, suggestions and bugs regarding Entity Framework support in ADO.NET Data providers
Post Reply
jeremyh
Posts: 1
Joined: Fri 13 Aug 2010 16:35

Self-tracking entities - Delete problem

Post by jeremyh » Fri 13 Aug 2010 16:40

Hi,

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? :(

AndreyR
Devart Team
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Post by AndreyR » Mon 16 Aug 2010 13:54

Could you please send me (support * devart * com, subject "EF4: STE Delete") a small test project illustrating the issue?
Please include the database script in it.
I have made a simple project but failed to reproduce the problem.

Post Reply