views:

347

answers:

1

I'm trying to build a modified role system that has the following class/relationship structure:

Project ProjectRole Employee

where

ProjectEmployee maps the three entities together.

I have a one-to-many mapping from Project to ProjectEmployee and a reference mapping from ProjectEmployee to Project.

I can add new ProjectEmployee's just fine (which means my Create activities are fine as well), but I want to constrain the relationship to have only one entry per Employee. This affects the logic of my Update activities.

In hacking this together, I am attempting to empty the Project.ProjectEmployees (by setting the value to a new List) and then adding a new instance of ProjectEmployee with the appropriate role, etc.

In doing this, I get an error that is related to setting Project.ProjectEmployees to an empty List.

"Cannot insert the value NULL into column 'ProjectId', table 'AppDB.dbo.ProjectEmployees'; column does not allow nulls. UPDATE fails. The statement has been terminated."

If I remove the line that news up the List, the subsequent records get added, but then I'm staring at too many records per employee.

Here's my Project -> ProjectEmployees mapping:

mapping.HasMany(x => x.ProjectEmployees) .Cascade.All() .WithKeyColumn("ProjectId");

And the mapping in ProjectEmployee -> Project:

mapping.References(x => x.Project, "ProjectId");

Should be simple right?

For what it's worth, I also added a method to my Project class called AddProjectEmployee that searches for the Employee in question, removes his ProjectEmployee if he exists, then adds the new ProjectEmployee. I get the same error when I call this.

Any help would be appreciated.

Nick

+1  A: 

This was cross-posted on the Fluent NHibernate group and answered there by Hudson Akridge. As Hudson said, the solution is to use Clear() on the collection as that allows NHibernate to track the changes (whereas newing up the collection causes the property to reference an instance NH doesn't know about).

Stuart Childs
Thanks Stuart. I saw the response on the FNH group as well, and the Clear did in fact resolve my issue.
mannish