Recently Oren (Ayende) had a serious of posts on NHibernate mappings and the various options you can configure using Xml mappings. This series of posts takes those examples and shows how you can use FluentNHibernate to configure the same mappings.
This is a companion post for Oren’s post on property mappings in NHibernate, here. I recommend reading his post before venturing forward.
In this post I’ll show how you use FluentNHibernate instead of using NHibernate’s xml mapping files.
Based on Oren’s original post on <property> mapping, here is the full mapping file:
<class name="Blog"
table="Blogs">
<id name="Id">
<generator class="identity"/>
</id>
<version name="Version"/>
<property name="Title" update="false"/>
<property name="Subtitle" optimistic-lock="insert"//>
<property name="AllowsComments" insert="false"/>
<property name="CreatedAt" />
<property name="CountOfPosts"
formula="(select count(*) from Posts where Posts.Id = Id)"/>
</class>
Below is the matching FluentNHibernate mapping:
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
WithTable("Persons");
Id(prop => prop.Id)
.GeneratedBy.Identity();
Version(prop => prop.Version);
Map(prop => prop.FirstName);
Map(prop => prop.LastName).SetAttribute("optimistic-lock", "false");
Map(prop => prop.DateOfBirth);
Map(prop => prop.Active).SetAttribute("generated", "insert");
Map(prop => prop.CountOfComments)
.FormulaIs("(Select Count('') from Comments Where Comments.CreatedBy = Id)");
}
}
A couple of notes:
- You can use the Version() method to specify a version property in your class.
- There is no inbuilt way to specify optimistic-lock attribute in FluentNHibernate right now, at least I couldn’t find one. But you can use the SetAttribute method to inject in the attribute value.
- Similarly, there is no inbuilt way to specify that a column value is generated by the database, but just like in the case of optimistic-lock, you can use the SetAttribute method to inject the attribute.
- FormulaIs can be used to specify a custom formula for a property.
1 comments:
Nice post ritesh.. am just venturing into the NH/FNH land and this helps
Post a Comment