So I ran into this error yesterday trying to delete a user which in turn has multiple collections that would be deleted too. You would think that I would have to manually delete the entire User tree, on collection at a time. Well the way thing work is that Entity framework will do the work for you if your tables are set to Cascade Delete. Now, you might see that error and be confused as to why it crops up even when you do have Cascade Delete on the needed tables. Here’s the situation:
As I said, I was trying to delete a user through the entity framework but noticed that all the addresses the user had were still in the database after deletion. Whoops. I dun forgot to set Cascade Delete on the tables. No big deal. So after I fixed the tables, I went to update the edmx file… ie update from database… and I thought all was well. Yeah not so much. I started to get this error. So the next thing I did was open the .edmx file in notepad and looked for “delete”. Sure enough I found it.
<Association Name="FK_UserAddress_User"> <End Role="ChatUser" Type="BAT.Data.Store.User" Multiplicity="1""> <OnDelete Action="Cascade" /"> </End">
Eh ok… it’s there. Well after some searching I ran into this post. Basically what was happening is although that shows the OnDelete Action=”Cascade”, it’s still not everywhere it needs to be. Then it dawned on me that the way the .edmx file works is that pretty much everything has to be doubled in the file, once for the database and once for the actual class. What was missing was the class half. For some reason when adding Cascade to a foreign key and then updating the .edmx file, only the table part of the markup gets updated. Bummer. So, what to do? Kind the foreign key name in the file (FK_UserAddress_User for example) and do a search on it. You’ll find something like this:
<Association Name="FK_UserAddress_User"> <End Type="BAT.Data.ChatUser" Role="User" Multiplicity="1" />
Oooo right there is the problem. You see, if this were correctly done, it would have the action=”delete” added to it, just like the one in the SSDL area. So how do you fix this? Manually. Hooray.
<Association Name="FK_UserAddress_User"> <End Type="BAT.Data.ChatUser" Role="User" Multiplicity="1" > //RIGHT HERE <OnDelete Action="Cascade"></OnDelete> //RIGHT HERE </End> //RIGHT HERE <End Type="BAT.Data.UserAddress" Role="UserAddress" Multiplicity="*" /></Association>
As you can see, it’s a simple change and you only have to do it to the object of Multiplicity=”1″, which of makes sense you wouldn’t want a user deleted if an address is. But it’s still annoying and a real pain if you have more than say one to fix.