An entry with the same key already exists.

I came across this error message the other day, working on a new ASP.NET 4 Dynamic Data Web site, and I was baffled as to what the problem was. I started troubleshooting and worked out that it happened with the Edit and Insert views. Okay, then I tried editing a row in all of my entities, just to see if any of them would work. I only had 8 tables at the time, so that wasn’t exactly a time consuming exercise. Much to my surprise, I was able to open one of the entities in the Edit view, but why so, when the others failed? I then looked at the number of columns exposed in the view and the entity that, for which the Edit view worked, only had a single column displayed. Then I tried hiding (ScaffoldColumn(False)) all columns but one in the metadata class for one of the partial entity classes, and then that worked. Now that worked, but it seemed a little silly, so I wasn’t going to let that beat me. After a while, I worked out that it happened when more than one column, displayed in the same type of UI control, or rather in this case a TextBox control, was used. So, I checked the associated Field Templates, and it was the validators attached to the TextBox control in the Text_Edit.ascx field control. Then it finally dawned upon me, it had to with the client ID’s of the controls. I looked at my web.config, in which I had this element:

masterPageFile="..." pageBaseType="..." clientIDMode="Static" />

Sure enough, removing the new ASP.NET 4.0 clientIDMode attribute and value fixed it. See Rick Strahl’s excellent article on this property,