$ cat "

Verifying IEnumerable<T> HasMany Mapping with Fluent NHibernate

"

Fluent NHibernate has built in functionality to make it very simple to verify that your entities are mapped correctly. To test the mappings of an entity you can use the PersistenceSpecification class:

[Test]
public void CanMapPost()
{
using (ISession session = SessionFactorySingleton.OpenSession())
{
new PersistenceSpecification<Post>(session)
.CheckProperty(p => p.Name, "Post Name")
.CheckProperty(p => p.DateTime, new DateTime(2009, 12, 6))
.CheckProperty(p => p.Comment, "Comment goes here")
.CheckProperty(p => p.Amount, 250.90)
.VerifyTheMappings();
}
}

This creates an instance of the Post class, saves it to the database, retrieves it again and verifies that its properties have the correct values.

The PersistenceSpecification class also includes functionality to verify HasMany and References mappings. For example, you could verify a HasMany mapping like this:

new PersistenceSpecification<Post>(session)
.CheckList(p => p.Tags, tags)

This works well if you have a setter for your collection. However, if you expose the collection as an IEnumerable<T> and use a private backing field, for example by mapping it as Access.CamelCaseField, it will not work. This is because of the fact that Fluent NHibernate does not know how to add the items to the collection.

This issue has been fixed in later releases of Fluent NHibernate. Now you can verify your IEnumerable<T> property mapping using the CheckEnumerable method of the PersistenceSpecification class. A complete verification of the post class above could look like this:

public void CanMapPost()
{
using (ISession session = SessionFactorySingleton.OpenSession())
{
var tags = new List<Tag>()
{
new Tag("tag 1"),
new Tag("tag 2")
};

new PersistenceSpecification<Post>(session)
.CheckProperty(p => p.Name, "Post Name")
.CheckProperty(p => p.DateTime, new DateTime(2009, 12, 6))
.CheckProperty(p => p.Comment, "Comment goes here")
.CheckProperty(p => p.Amount, 250.90)
.CheckEnumerable(p => p.Tags, (p, t) => p.AddTag(t), tags)
.VerifyTheMappings();
}
}

Written by Erik Öjebo 2009-12-07 21:15

    Comments