Wednesday, 30 January 2008

Linq DeleteOnNull

During development of our project using Linq I came across a situation where I needed to remove a relationship between two objects, this should be simple enough right?

So I looked at the EntitySet<T> class, low and behold this had a method called Remove<T>(), excellent I thought, I'll just call that and everything will be fine. Nope, so the following code will not work the way you expect it to, you get some dodgy error about not being able to set the value to null.

                    ClubGroupMap linq = entitySet[index];
ClubGroupMapEntity entity = entities.FirstOrDefault<ClubGroupMapEntity>(c => c.Club.Id == linq.ClubID);
if (entity == null)
{
entitySet.Remove(linq);
}



Anyway, it turns out that in order to remove relationship data (stuff in a foreign key table) from the database via Linq, you need to set the parent object reference explicitly to null. For more info on this see: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1681314&SiteID=1, basically the Linq object should have the DeleteOnNull parameter of the Association attribute set to true, this them tells Linq that it is able to delete the object when the reference to its parent is null. So the code should look like this:



                    ClubGroupMap linq = entitySet[index];
ClubGroupMapEntity entity = entities.FirstOrDefault<ClubGroupMapEntity>(c => c.Club.Id == linq.ClubID);
if (entity == null)
{
entitySet.Remove(linq);
linq.Club = null;
linq.ClubGroup = null;
}



If you are using SQLMetal to generate the Linq data context on the fly (like we were) you need to make sure that the database has been configured to correctly use cascade deletes.

No comments: