Tags: , | Categories: C#, Fluent, NHibernate Posted by Admin on 11/21/2011 4:06 PM | Comments (1)

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;
    }
}

Comments (1) -

Ferdinand Servano United Kingdom on 4/15/2012 4:36 PM Brilliant idea ... ;)

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading