Archive for June, 2010
Fluent NHibernate References – Left Join (Sort of)
I hit an issue yesterday with NHibernate which I managed to resolve so I thought I’d jot down some notes.
The problem was as follows:
We have a class called Person see below:
[sourcecode language='c#']
public class Person
{
public virtual int Id { get; set; }
public virtual Car Car { get; set; }
}
[/sourcecode]
Using Fluent NHIbernate we initially set up our mapping as follows:
[sourcecode language='c#']
public class PersonMap : PersonMap
{
public PersonMap()
{
Table(“Person”);
Id(x => x.Id).Column(“PersonId”);
References(x => x.Car).Column(“CarId”);
}
}
[/sourcecode]
As you can see Person has a reference to class Car. The problem we have is that a Person may or may not have a Car.
With the above mapping NHibernate assigns each Person object its related Car object if one is available. If no Car object is available NH creates a “Lazy” dynamic proxy object. This is not what we want, particularly as we might want to serialize the Person object over WCF. What we really wanted was for the Car property to be set to null if no car is available.
Anyway with a bit of digging around I found that these could be easily achieved by tweaking the mapping as follows:
[sourcecode language='c#']
public class PersonMap : ClassMap
{
public PersonMap()
{
Table(“Person”);
Id(x => x.Id).Column(“PersonId”);
References(x =>x.Car).Column(“CarId”).NotFound.Ignore().Not.LazyLoad().Nullable();
}
}
[/sourcecode]
Now, if no Car is available the Car property is set to null.