So, Country has a collection of Counties
public class Country
{
private IList<County> counties = new List<County>();
public virtual IList<County> Counties
{
get { return this.counties; }
set { this.counties = value; }
}
}
Therefore County has a reference to Country
public class County
{
public virtual Country Country { get; set; }
}
I was trying to create a new County and then add it to the Counties collection of a Country instance
public static void Something()
{
Country country = repository.Get<Country>(countryId);
County county = new County(){ Name = "Berkshire" };
country.Counties.Add(county); //this executes
repository.Save<Country>(country); //this bails
}
The solution was to test the parent Country's County collection within the Country setter of the County class
public class County
{
private Country country = null;
public virtual Country Country
{
get { return this.country; }
set
{
this.country = value;
if (!this.country.Counties.Contains(this))
{
this.country.Counties.Add(this);
}
}
}
}
Why? Well I don't really know, but it works. I guess that there is something going on within NHibernate and object tracking, but that is just a guess!
For a more fluent way of doing the same thing
public class County
{
public virtual Country Country { get; protected set; }
public virtual County WithCountry(Country country)
{
this.country = value;
if (!this.country.Counties.Contains(this))
{
this.country.Counties.Add(this);
}
return this;
}
}
7e6cbe0f-d795-41a8-a6d4-45167941cf0e|0|.0