Tutorial :Mapping a backing field, that has a different type from the respective property, using Fluent NHibernate


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.


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://nhibernate.info/doc/nh/en/index.html#collections-onetomany


Found a post about it: https://web.archive.org/web/20090831052429/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:


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »