tags:

views:

823

answers:

2

I have a User class which may or may not have an associated Department. This is referenced through the foreign key DepartmentId, and the relevant field in the User table is set to allow nulls.

When I set up my "Create User" form and select no Department, I get a conflict error on SubmitChanges():

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_User_Department".

How can I convince Linq to SQL to insert a NULL when the "Department" has been selected as the "blank" first option?

Or, perhaps, is there a keyword I am missing for the "optionLabel" parameter of the Html.DropDownList method that does this? I am currently using "None" because using null or "" cause no "blank option" to be displayed, and I suspect that this may be contributing to the problem. Thanks for any assistance.

A: 

You could have an entry "N/A" in Department which you assign when no department is selected. Then you wouldn't get a foreign key conflict.

sepang
+1  A: 

I have found a less-than-desirable solution by putting the following in my UsersController.Create method:

// Snipped UpdateModel call
if (form["User.DepartmentId"].Length == 0)
{
    createdUser.DepartmentId = null;
}
Models.User.DataContext.SubmitChanges();

Does anyone have anything cleaner / automatic?

tags2k