A fluent interface to NHibernate - Part 2 - Value Objects

In my last post I introduced a new framework which gives you the possibilities to define the mappings of the entities to the underlying database in C# using a fluent interface instead of writing XML mapping files. This has caused some discussion in the community on the pros and cons of this approach.

Let me repeat what the goals of this new framework are or should be

  • reduce friction when mapping entities (and value objects) to the underlying database
  • mapping should be more expressive than use of plain XML
  • mapping should be more testable
  • flexible, that is: allow the use of mapping conventions

How to map common scenarios

Now let's have a look at some common scenarios which you encounter daily in a moderately complex domain model. Let's concentrate on how these scenarios are mapped by using the fluent interface.

Scenario 1: Value Objects

In DDD you have the notion of entities and value objects. The latter are immutable and have no identity. In NHibernate they are mapped as Component and its fields are embedded in the same table as the containing entity.

A typical value object is Money which represents a monetary value. Let's define the following simple domain model

image

We have an account which is an entity and the account contains a property of type Money (called Balance). Balance is now a value object and contains not only the amount but also the currency in which the value is expressed (Note: 100 US$ is different than e.g. 100 €). The code for the money class

public class Money
{
    private Money()
    {
    }
 
    public Money(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }
 
    public virtual decimal Amount { get; private set; }
    public virtual string Currency { get; private set; }
}

Note that the properties are read only since any value object is immutable (once set you cannot change it). The private parameter-less constructor is there ONLY to satisfy NHibernate which needs it. But since it is private we cannot accidentally use it.

The code for the Account class is trivial

public class Account : Entity
{
    public virtual string Name { get; set; }
    public virtual Money Balance { get; set; }
}

Note that Account inherits from the Entity base class which is implemented in the framework. As discussed in my previous post I regard this as a limitation of the framework. This requirement possibly will be eliminated in future versions of the framework.

How can we map this scenario? Let's have a look at the necessary code

public class AccountMap : ClassMap<Account>
{
    public AccountMap()
    {
        Id(x => x.Id);
 
        Map(x => x.Name)
            .CanNotBeNull()
            .WithLengthOf(50);
        
        Component<Money>(x => x.Balance, m =>
                                             {
                                                 m.Map(x => x.Amount, "BalanceAmount");
                                                 m.Map(x => x.Currency, "BalanceCurrency");
                                             });
    }
}

Easy, isn't it? First we map the property Id of our account entity (inherited from the base Entity class). Then we map the Name property. We declare that it cannot be null and that it's maximal length should not exceed 50 characters.

Finally we map the Balance property which is a value object an thus treated by NHibernate as Component. Here I have used the second (optional) parameter of the map function which is the name of the table column to which the respective property should be mapped. When we create the database schema from this mapping it will contain one table called Account which contains the four columns Id, Name, BalanceAmount and BalanceCurrency.

Scenario 2: Entity with multiple properties of same value object type

How does this fit for a scenario where I have an entity which has more than one property of the same value object type? Let's have a look at the following simple model. An Employee entity has a HomeAddress and a WorkAddress field. Both fields are of type Address. Address is a value object.

image

Again the code for the Address value object (which is immutable!)

public class Address
{
    public virtual string AddressLine1 { get; private set; }
    public virtual string AddressLine2 { get; private set; }
    public virtual string PostalCode { get; private set; }
    public virtual string City { get; private set; }
    public virtual string Country { get; private set; }
 
    private Address()
    {
    }
 
    public Address(string addressLine1, string addressLine2, string postalCode, string city, string country)
    {
        AddressLine1 = addressLine1;
        AddressLine2 = addressLine2;
        PostalCode = postalCode;
        City = city;
        Country = country;
    }
}

and the Employee entity

public class Employee : Entity
{
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual Address HomeAddress { get; set; }
    public virtual Address WorkAddress { get; set; }
}

Now let's have a look at the mapping code

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Id(x => x.Id);
        Map(x => x.FirstName).CanNotBeNull().WithLengthOf(20);
        Map(x => x.LastName).CanNotBeNull().WithLengthOf(20);
 
        Component<Address>(x => x.HomeAddress,
                           a =>
                               {
                                   a.Map(x => x.AddressLine1, "Home_AddressLine1");
                                   a.Map(x => x.AddressLine2, "Home_AddressLine2");
                                   a.Map(x => x.PostalCode, "Home_PostalCode");
                                   a.Map(x => x.City, "Home_City");
                                   a.Map(x => x.Country, "Home_Country");
                               });
 
        Component<Address>(x => x.WorkAddress,
                           a =>
                               {
                                   a.Map(x => x.AddressLine1, "Work_AddressLine1");
                                   a.Map(x => x.AddressLine2, "Work_AddressLine2");
                                   a.Map(x => x.PostalCode, "Work_PostalCode");
                                   a.Map(x => x.City, "Work_City");
                                   a.Map(x => x.Country, "Work_Country");
                               });
    }
}

Note that we have to explicitly name the underlying columns here (e.g. "Home_City" versus "Work_City") otherwise the schema generation would fail.

Honestly, I don't like the above code since it is not DRY. So let's refactor it...

public class EmployeeMap : ClassMap<Employee>
{
    private Action<ComponentPart<Address>> MapAddress(string columnPrefix)
    {
        return a =>
                   {
                       a.Map(x => x.AddressLine1, columnPrefix + "AddressLine1");
                       a.Map(x => x.AddressLine2, columnPrefix + "AddressLine2");
                       a.Map(x => x.PostalCode, columnPrefix + "PostalCode");
                       a.Map(x => x.City, columnPrefix + "City");
                       a.Map(x => x.Country, columnPrefix + "Country");
                   };
    }
 
    public EmployeeMap()
    {
        Id(x => x.Id);
        Map(x => x.FirstName).CanNotBeNull().WithLengthOf(20);
        Map(x => x.LastName).CanNotBeNull().WithLengthOf(20);
 
        Component<Address>(x => x.HomeAddress, MapAddress("Home_"));
        Component<Address>(x => x.WorkAddress, MapAddress("Work_"));
    }
}

I have extracted the mapping of the address into a helper method and can now call it as many times as I have to and just have to provide the table column prefix to be used for all fields of the address. What I still don't like in the above approach is that I need an internal helper method to map my addresses. What if I have another entity (say Customer) which also has one or several properties of type Address?

It would be nice if the framework would provide some component mapper.

Since I cannot rely on the framework at the moment I have found the following more elegant solution, where the mapping of the Address value object is externalized into it's own mapper class

public class AddressMap
{
    public static Action<ComponentPart<Address>> WithColumnPrefix(string columnPrefix)
    {
        return a =>
        {
            a.Map(x => x.AddressLine1, columnPrefix + "AddressLine1");
            a.Map(x => x.AddressLine2, columnPrefix + "AddressLine2");
            a.Map(x => x.PostalCode, columnPrefix + "PostalCode");
            a.Map(x => x.City, columnPrefix + "City");
            a.Map(x => x.Country, columnPrefix + "Country");
        };
    }
}

and then the Employee mapper class can be simplified to this

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Id(x => x.Id);
        Map(x => x.FirstName).CanNotBeNull().WithLengthOf(20);
        Map(x => x.LastName).CanNotBeNull().WithLengthOf(20);
 
        Component(x => x.HomeAddress, AddressMap.WithColumnPrefix("Home_"));
        Component(x => x.WorkAddress, AddressMap.WithColumnPrefix("Work_"));
    }
}

Well, I'm now quite happy with my solution.

Testing the mapping

Now let's write a test for the mapping. A simple test which verifies that the mapping is correct and that a record can be written to the database is quite easy to implement

[TestFixture]
public class Employee_Fixture : FixtureBase
{
    [Test]
    public void Verify_that_employee_saves()
    {
        var emp = new Employee
                      {
                          FirstName = "Gabriel",
                          LastName = "Schenker",
                          HomeAddress = new Address("Castle home", null, "8888", "Paradise", "Switzerland"),
                          WorkAddress = new Address("My work place", null, "7777", "Atlantis", "Pegasus")
                      };
        Session.Save(emp);
 
        Session.Flush();
        Session.Clear();
 
        var fromDb = Session.Get<Employee>(emp.Id);
        Assert.AreNotSame(emp, fromDb);
        Assert.AreEqual(emp.FirstName, fromDb.FirstName);
        Assert.AreEqual(emp.LastName, fromDb.LastName);
        Assert.AreEqual(emp.HomeAddress.AddressLine1, fromDb.HomeAddress.AddressLine1);
        Assert.AreEqual(emp.HomeAddress.AddressLine2, fromDb.HomeAddress.AddressLine2);
        Assert.AreEqual(emp.HomeAddress.PostalCode, fromDb.HomeAddress.PostalCode);
        Assert.AreEqual(emp.HomeAddress.City, fromDb.HomeAddress.City);
        Assert.AreEqual(emp.HomeAddress.Country, fromDb.HomeAddress.Country);
        Assert.AreEqual(emp.WorkAddress.AddressLine1, fromDb.WorkAddress.AddressLine1);
        Assert.AreEqual(emp.WorkAddress.AddressLine2, fromDb.WorkAddress.AddressLine2);
        Assert.AreEqual(emp.WorkAddress.PostalCode, fromDb.WorkAddress.PostalCode);
        Assert.AreEqual(emp.WorkAddress.City, fromDb.WorkAddress.City);
        Assert.AreEqual(emp.WorkAddress.Country, fromDb.WorkAddress.Country);
    }
}
Note that the test fixture inherits from the FixtureBase class which I have described in my previous post. Further note that I use SqlLite as my in-memory database for testing. Let's run the test. Well, it passes as we expected.
But now let's use the framework to help reduce some code. As shown in my previous post we can use the PersistenceSpecification class of the mapping framework for this purpose. A test looks like follows
 
[Test]
public void Verify_that_employee_saves_revisited()
{
    new PersistenceSpecification<Employee>(Session)
        .CheckProperty(x=>x.FirstName, "Gabriel")
        .CheckProperty(x=>x.LastName, "Schenker")
        .CheckProperty(x => x.HomeAddress, new Address("Castle home", null, "8888", "Paradise", "Switzerland"))
        .CheckProperty(x => x.WorkAddress, new Address("My work place", null, "7777", "Atlantis", "Pegasus"))
        .VerifyTheMappings();
}
Let's run this test. Ooops, the result of the test is red! See chapter Update below!

image

The problem is that SqlLite is local to a session. That is, whenever I open a new session I have another (in-memory) database. And since the actual implementation of the PersistenceSpecification class uses a new session to test we have the problem that we now don't have access to the original schema prepared for the test.

So, what can we do? Ok, once again we have to fix the PersistenceSpecification and implement a constructor which takes an existing open session to execute the test.

The problematic code of the PersistenceSpecification class is here

image

I tried to fix it, but a quick and dirty solution didn't work. There has to be done some major re-factoring...

Update (15. Aug. 2008)

The contributors to the framework have worked hard. They changed the implementation of the PersistenceSpecification class such as that it now works also with the SqLite in-memory database. The above test is now working as it should.

Source Code

You can get the source code of the solution accompanying this post here.

Summary

In this post I discussed the mapping of complex entities having one to many properties which are value objects. I have shown that a mapping is possible with the current release of the mapping framework. The PersistenceSpecification class of the framework which should decrease the work to do for testing does not currently work with a SqlLite in-memory database. The PersistenceSpecification class of the framework which decreases the work to do for testing now works also with the SqLite in-memory database.

Enjoy

Blog Signature Gabriel .

Print | posted on Wednesday, August 13, 2008 11:04 AM

Comments on this post

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Rev 51 committed. PersistenceSpecification now uses the same session (with a Flush+Clear in the middle).
Left by Chad Myers on Aug 14, 2008 3:48 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
@Chad: thanks. Will update this post shortly!
Left by Gabriel Schenker on Aug 15, 2008 1:48 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Wooww. This looks so cool. I'll definitely be wanting more =p~

Very nice. Please post some more :D

Kudos
Left by Mihai on Aug 18, 2008 7:59 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
@Mihai: note that part 3 is already posted and further parts will follow soon!
Left by Gabriel Schenker on Aug 18, 2008 9:58 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Hi Gabriel,

When running the tests in your solution, I get errors with SQLite:
Could not create the driver from NHibernate.Driver.SQLite20Driver.
The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found.

Tried google but couldn't find anything to my aid. Do you know how to fix this?

KR,
Tom
Left by Tom on Oct 20, 2008 7:59 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Hello.

Is it me or you're calling a virtual method from within the constructor? I believe that is not the recommended approach. I've just started looking at the code, but it seems like there really isn't any other method which I can overwrite for introducing my definitions...am I wrong?
Left by Luis Abreu on Oct 20, 2008 10:13 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
@Tom: did you select "copy always" as option for "copy to output directory" for the System.Data.Sqlite assembly? Obviously the file is not found in the bin directory when the code is executed...
eventually you could have a problem with R# (are you using it?). Just tell R# not to use shadowed assemblies during test
Left by nhibernate on Oct 21, 2008 7:13 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
@Luis: the problem is, that NHibernate forces me to use virtual methods. But it's no problem here. It's just a hint of R# (a guideline) which you can ignore in THIS case.
Left by nhibernate on Oct 21, 2008 7:16 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
"copy always" as option for "copy to output directory" is selected for the dbfile. On the reference it's just "copy local" "true".

Yes, I'm using r# and I have disabled "shadow-copy assemblies being tested" but that made no difference.
Left by Tom on Oct 22, 2008 12:38 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Hi Gabriel,
THX THX THX! One of the best postings i've ever read about nhibernate and doing good sw-architecture :-)

g
Helmut
Left by zyko on Jan 07, 2009 10:35 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
I get errors with SQLite:
Could not create the driver from NHibernate.Driver.SQLite20Driver.
The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found.
Left by club penguin on Jun 02, 2009 7:30 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Nice post,
I get errors with SQLite:
Could not create the driver from NHibernate.Driver.SQLite20Driver.
The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found.
I cannot find the solution any where

Thanks for writing about it
Left by software development company on Aug 19, 2009 5:41 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
I get errors with SQLite:
Could not create the driver from NHibernate.Driver.SQLite20Driver.
The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found.
Left by luxury Car seats on Oct 29, 2009 3:40 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
You're right, this makes mapping so much easier!
Left by Kids Games on Nov 23, 2009 11:11 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
It is better have your blog at hand than just searching on the web all the time.
Left by students with autism on Dec 03, 2009 1:28 AM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
I have web based application which used sql reporting services to generate web based reports. Myapplication has dynamic column reports. Entire application get displayed in a pop window ,hence there is no proble with sql injection. But while I do import to excel or any other format it opens another browser where I found the Sql injection (my sql clause).This can be achieved if there is any fascility to use form post method. If this is possible then please let me know the configuration or any other solution.
Left by online nl casino’s on Dec 17, 2009 11:53 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Wooww. This looks so cool. I'll definitely be wanting more =p~

Very nice. Please post some more :D
Left by pandora jewelry on Dec 24, 2009 11:58 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
Thanks for your useful info, I think it's a good topic
Left by Russell blog on Jan 12, 2010 2:52 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
thats the way i like it
Left by make money online on Jan 16, 2010 1:19 PM

# re: A fluent interface to NHibernate - Part 2 - Value Objects

Requesting Gravatar...
What's more, a bracelet can also be equipped with different small pandora jewelry and even you can change it according to your mood at any time. Here are some meanings of pendant. Small Plane stands for traveling and adventure ; anchor, stability and hope; your baby's boots, having a lot of babies; small feeding pandora bracelets abundant food; Church means happiness and stability of marriage; dragonfly means riches; Eiffel Tower means travel and exploration; four-leaf clover means fortune; horseshoe means luck; Nest means a happy family; bride shows a happy bride in her coming pandora jewelleryship steering shows calming and confidence; pandora ukcoin pandora beadsshows rich marriage life. Wish bone, dreams being about to come true; pandora charm bracelets, love; one heart shot by an arrow, romantic love; purse, wealth; and heart-shaped lock, true love.olkjkjhyu
Left by pandora jewelry on Jan 28, 2010 6:48 PM

# ghd hair

Requesting Gravatar...
To be under the spotlight of people with beautiful[url=http://www.myghdhairs.com] GHD hair straighters[/url] darning hair has haunted the dream of many MM. Girls, with no exception, wish their beautiful straight hair could add to their beauty greatly. And this has brewed the fashion of the
devices. With it [url=http://www.myghdhairs.com] GHD hair straighterscheap GHD[/url] s sound quality and unique design, it has become the GHD hair straighterspecial preference of many girls' first choices. What the unique characteristics of the
[url=http://www.myghdhairs.com] GHD hair straighters[/url] ?
GHD has been leading the hair fashion for a long time, and has been the ideal choice to the fashion-chasing women all around the world. No doubt, the new brand [url=http://www.myghdhairs.com] GHD hair straighters[/url] has enjoyed the most popularity among all sorts of hair-beauty devices which has been served as the “idol brand” in the market for a long time.
Left by igwg on Feb 02, 2010 6:12 PM

Your comment:

 (will show your gravatar)
 
Please add 2 and 1 and type the answer here: