views:

114

answers:

2

This one has me stumped, despite the numerous posts on here.

The scenario is a basic MVC(2) web application with simple CRUD operations. Whenever the edit form is submitted and the UpdateModel() called, an exception is thrown:

System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException was unhandled by user code

This occurs against a DropDownList value which is a foreign key on the entity table. However, there is another DropDownList list on the form, representing another foreign key, which does not throw the error (unsurprisingly). Changing the property values manually inside the Edit Action:

Recipe recipe = repository.GetRecipe(int.Parse(formValues["recipeid"]));
recipe.CategoryId = Convert.ToInt32(formValues["CategoryId"].ToString());
recipe.Page = int.Parse(formValues["Page"].ToString());
recipe.PublicationId=Convert.ToInt32(formValues["PublicationId"].ToString());

Allows the CategoryId and Page properties to be updated, and then the error is thrown on the PublicationId. All of the referential integrity is checked an the same in the db and the dbml.

Any light shed on this would be most welcome.

+2  A: 

This error has nothing whatsoever to do with model binding. Rather, it's strictly related to LINQ to SQL. You can find a reasonable explanation of what causes it in this post.

Craig Stuntz
Appreciate the input Craig. I had seen this post, but couldn't reconcile 2 facts:1. Until recently (I came back to this pet project after a couple of months - and some framework installs later) this worked fine.2. The CategoryId updates fine. It also is a FK constraint, but I notice that the EntityRef has not been created despite the db constraints - Looks like there's something squiffy in the dbml creation.Thanks.
OldBoy
A: 

Change your code with below

instead of

recipe.CategoryId = Convert.ToInt32(formValues["CategoryId"].ToString());

write this

recipe.Category = db.GetCatById(formValues["CategoryID"]);
Barbaros Alp