views:

18

answers:

2

I need to persist this class on database using Fluent NHibernate:

public class RaccoonCity 
{
    public virtual int Id { get; private set; }

    public virtual DateTime InfectionStart { get; private set; }

    private IList<Zombie> _zombies = new List<Zombie>();

    public virtual IEnumerable<Zombie> Zombies
    {
        get { return _zombies; }
    } 
    protected RaccoonCity()
    {}

    public RaccoonCity(DateTime startMonth)
    {
        InfectionStart = startMonth;
    }

    public virtual void AddZombie(Zombie z)
    {
        _zombies.Add(z);
    }

}

The property has type IEnumerable to indicate that you shouldn´t use it to insert new items. The backing field is of IList to make it easy to insert new items from the own class.

Zombie is a simple class:

public class Zombie
{
    public virtual int Id { get; private set; }
    public virtual string FormerName { get; set; }
    public virtual DateTime Infected { get; set; }
}

The map is the following:

public class RaccoonCityMap: ClassMap<RaccoonCity> 
{
    public  RaccoonCityMap()
    {
        Id(x => x.Id);
        Map(x => x.InfectionStart);
        HasMany(x => x.Zombies)
            .Access.CamelCaseField(Prefix.Underscore)
            .Inverse()
            .Cascade.All();
    }
}

When I test this, the data is inserted in database, but the zombie´s foreign keys are empty, and the RaccoonCity instance has zero items on Zombies list.

Any ideas?

A: 

Found a post about it: http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/08/15/a-fluent-interface-to-nhibernate-part-3-mapping.aspx

I had to implement the method HasManyComponent by myself since it was missing in the actual trunk of the framework. That is, it was not possible to map a collection of value objects. But it has not been that hard since the source base is really nice. My changes will probably be integrated into the framework soon.

And this one:

http://nhforge.org/blogs/nhibernate/archive/2008/09/06/a-fluent-interface-to-nhibernate-part-3-mapping-relations.aspx

Seiti
A: 

You are declaring the relationship as Inverse, which means the Zombie and not the RacoonCity is responsible for maintaining the relationship.

Either add the corresponding reference to zombie and set it on the AddZombie method, or remove the Inverse (in that case, you'll see an INSERT with a null FK followed by an update).

Suggested reading: http://nhforge.org/doc/nh/en/index.html#collections-onetomany

Diego Mijelshon
Thanks! "Inversion" was not real clear to me. I thought that the class responsible to persists itself was the class himself. And "Inverse" puts this responsibility on other classes shoulders...
Seiti
Exactly. I agree that the nomenclature is not the most intuitive, but it has its roots on the original Java Hibernate.
Diego Mijelshon