LINQ Exception: System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException

来源:互联网 发布:服装零售店软件 编辑:程序博客网 时间:2024/05/22 07:43

There are two relationed tables



When want use the following code to update the record in table cat_user, it will meet an Exception:

System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException


 var cu = dc.cat_users.FirstOrDefault(c => c.uid == can.uid);                               if (list_cat.Visible == true && cu.category.levels == 1 || cu.category.levels == 2)                {                    int selectedvalue = Convert.ToInt32(list_cat.SelectedValue);                    cu.cid = selectedvalue;                }


Change the code like following, it will update successful


 var cu = dc.cat_users.FirstOrDefault(c => c.uid == can.uid);                               if (list_cat.Visible == true && cu.category.levels == 1 || cu.category.levels == 2)                {                    int selectedvalue = Convert.ToInt32(list_cat.SelectedValue);                    cu.category = dc.categories.Single(c=>c.cid == selectedvalue);                }






原创粉丝点击