Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Entity Framework - Delete With Association Error
Published: 5/5/2009
XMl / RSS

When working with the Entity Framework and deleting an object that has a foreign key association to another object and that other object is loaded into memory, deleting the parent object will result in the following error:

Entities [ENTITYNAMES] in participate in the relationship [RELATIONSHIPNAME]. 0 related [ENTITY NAME] were found. 1 is expected.

This occurs despite the fact that the delete is valid given the foreign key constraints in the database, and suprisingly (or not) is by design. The problem is caused by the associated relationship objects that are loaded into memory when you load (or include) a relationship.

Unfortunately, this means that if you use the Include property of an EntityDataSource to load associated items for bound display, the Delete command (which would normally take care of the delete for you without requiring any code) will fail with the above error.

The only solution for this is to handle the RowDeleting event of the GridView and perform the delete yourself with an instance of an entity that does not have any loaded associations.



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.