I have a database with 3 tables:
- Project
- Sponsor
- ProjectSponsor
In my domain objects, i have an object Project which has a child property called Sponsors which is a list of ProjectSponsor objects, like this:
IList<ProjectSponsor> Sponsors;
here is the Nhibernate Mapping code:
ProductMap:
HasMany(x => x.Sponsors).AsBag().Inverse().Cascade.AllDeleteOrphan();
ProductSponsorMap:
References(x => x.Project).Not.Nullable();
References(x => x.Sponsor).Not.Nullable();
here is my Domain Objects:
public class Project
{
public virtual IList<ProjectSponsor> Sponsors { get; set; }
}
public class ProjectSponsor
{
public virtual Project Project { get; set; }
public virtual Sponsor Sponsor { get; set; }
}
ok . . now to my issue, when i try to add new Projects (with their associated projectsponsor) into the database.
Here is my code:
foreach (Project project in newProjects)
{
Repository.Save(project);
foreach (ProjectSponsor projectSponsor in project.Sponsors)
{
Repository.Save(projectSponsor);
}
}
I am getting an exception on this line:
Repository.Save(projectSponsor);
saying that not-null property reference a null or transient value is trying to be saved:
projectSponsor.Project is the property that its complaining about. I would have thought that would be set by default based on the nhibernate mapping.
do i really need to have an explicit piece of code that have this code:
projectSponsor.Project = project
or is there anything wrong with my mapping files ?
If you haven’t set the
projectSponsor.Projectproperty (and no code here says you have) then it will have the default value of null which will violate the mapping condition you’ve placed.NHibernate is just going to reflect the state of the objects and the state of the objects is – for want of a better word – broken as is. You could remove the Project property on the ProjectSponsor map and all would be well but you’re losing functionality to do so because obviously the directionality of relationships in OO is the reverse of RDBM directionality.
I would expect something like: