<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ivan Zlatev &#187; NHibernate</title>
	<atom:link href="http://ivanz.com/tag/nhibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://ivanz.com</link>
	<description></description>
	<lastBuildDate>Sun, 22 Apr 2012 18:15:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Three new featurelets for Fluent NHibernate</title>
		<link>http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/</link>
		<comments>http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/#comments</comments>
		<pubDate>Sun, 13 Dec 2009 17:58:21 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=702</guid>
		<description><![CDATA[<a href="http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/" title="Three new featurelets for Fluent NHibernate"></a>Lately I have been using Fluent NHibernate and NHibernate respectively for my ORM (Object-Relational Mapping) when working on my top secret pet project. Simply put &#8211; it&#8217;s great. Mapping is done using a fluent C# interface which makes use of &#8230;<p class="read-more"><a href="http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/" title="Three new featurelets for Fluent NHibernate"></a><p>Lately I have been using <a href="http://fluentnhibernate.org/">Fluent NHibernate</a> and <a href="http://nhforge.org">NHibernate</a> respectively for my ORM (Object-Relational Mapping) when working on my top secret pet project. Simply put &#8211; it&#8217;s great. Mapping is done using a fluent C# interface which makes use of lambda expressions for referencing properties instead of strings (check my <a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/">previous post</a> for more info) so the domain model is <strong>safe to refactor</strong> because the mapping will be kept up-to-date too.</p>
<p>I spend some time hacking on Fluent NHibernate to add three little features I needed for my integration unit testing via Fluent NHibernate&#8217;s <em>PersistenceSpecification</em>. They all currently live in my GitHub(also used by Fluent NHibernate) fork <a href="http://github.com/ivanz/fluent-nhibernate">here</a> and have all been submitted upstream. <strong>UPDATE:</strong> The changes are as of now (21.12.2009) officially part of Fluent NHibernate. I can only hope you will find them useful as well.</p>
<h3>PersistenceSpecification: More Informational Error Reporting</h3>
<p>Particularly useful to troubleshoot failing mapping integration unit tests when a property check fails it will print both expected and actual types of the values. Also notice that chained properties (object.PropA.PropB) are now supported as well:</p>
<p style="padding-left: 30px;"><em>For property &#8216;Nutrition.Calories&#8217; expected &#8217;400&#8242; of type &#8216;System.Int32&#8242; but got &#8217;400&#8242; of type &#8216;System.Single&#8217;.</em></p>
<p>instead of:</p>
<p style="padding-left: 30px;"><em>Expected &#8217;400&#8242; but got &#8217;400&#8242; for Property &#8216;NutritionCalories&#8217;</em></p>
<h3>PersistenceSpecification: Entity Components Property Testing</h3>
<p>It is now possible to test entity component properties. For example given this domain model:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Food
{
    public Food ()
    {
        Nutrition = new NutritionInfo ();
    }

    public virtual NutritionInfo Nutrition { get; protected set }
    public virtual int Id { get; set; }

}

public class NutritionInfo
{
    public virtual float? Fat { get; set; }
}
</pre>
<p>and this mapping:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FoodMap : ClassMap&lt;Food&gt;
{
    public FoodMap ()
    {
        Id (food =&gt; food.Id)
            .GeneratedBy.Native ();

        Component&lt;NutritionInfo&gt; (food =&gt; food.Nutrition,
            mapping =&gt; {
                mapping.Map (nutrition =&gt; nutrition.Fat)
                    .Nullable ();
            }
        ).Access.BackingField ();
    }
}
</pre>
<p>One can now use this in unit tests:</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod]
public void Food_Mapping ()
{
    new PersistenceSpecification&lt;Food&gt; (Session)
    .CheckProperty (food =&gt; food.Id, 1)
    .CheckProperty (food =&gt; food.Nutrition.Fat, 40f) // &lt;-- This one
    .VerifyTheMappings ();

}
</pre>
<p>Prior to my patch this wasn&#8217;t possible because Fluent Nhibernate <em>PersistenceSpecification</em> did not support chained properties and was trying to set a <em>Fat</em> property on the <em>food</em> object. Note that this is useful only for components and <span style="text-decoration: underline;">not</span> references. For the latter <em>.CheckReference (&#8230;) </em>should be used which will also commit the reference to the Database before doing anything else.</p>
<h3>PersistenceSpecification: IEqualityComparer for Individual Properties</h3>
<p>Given the setup from above it is now possible to set an IEqualityComparer per property, e.g.:</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod]
public void Serving_Mapping ()
{

    new PersistenceSpecification&lt;Food&gt; (Session, new EqualityComparerForAllProperties ())
    .CheckProperty (food =&gt; food.Id, 1)
    .CheckProperty (food =&gt; food.Nutrition.Fat, 40f, FloatEqualityComparer.Instance)
    .VerifyTheMappings ();
}
</pre>
<p>If there is no comparer set for the property it will fall back to using the <em>EqualityComparerForAllProperties</em> and if that is not specified it will just use Object.Equals.</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=702" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2009/12/13/three-new-featurelets-for-fluent-nhibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to avoid passing property names as strings using C# 3.0 Expression Trees</title>
		<link>http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/</link>
		<comments>http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 19:08:20 +0000</pubDate>
		<dc:creator>Ivan Zlatev</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://ivanz.com/?p=699</guid>
		<description><![CDATA[<a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/" title="How to avoid passing property names as strings using C# 3.0 Expression Trees"></a>Referencing property names via strings is evil. Consider this simplistic example: If at some point the property gets renamed the code will compile fine but a bug will be introduced as all those strings that contain the property name will &#8230;<p class="read-more"><a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/" title="How to avoid passing property names as strings using C# 3.0 Expression Trees"></a><p>Referencing property names via strings is evil. Consider this simplistic example:</p>
<pre class="brush: csharp; title: ; notranslate">
private int _myProperty;

public int MyProperty
{
    get { return _myProperty; }
    set {
        _myProperty = value;
        NotifyPropertyChanged (this, &quot;MyProperty&quot;)
    }
}

// Somewhere in a different project or file...
private void NotifyPropertyChanged (object sender, string propertyName)
{
    if (propertyName == &quot;MyProperty&quot;)
        Console.WriteLine (&quot;Property Changed&quot;);
}
</pre>
<p>If at some point the property gets renamed the code will compile fine but a bug will be introduced as all those strings that contain the property name will remain unchanged. Evil.</p>
<p>So I have been toying with NHibernate lately and yesterday I was writing some repositories. Let&#8217;s assume that theoretically they look like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Repository &lt;TEntity&gt;
{
    public virtual TEntity FindById (object id)
    {
        ...
    }
}

public class UserRepository : Repository&lt;User&gt;
{
    public IList&lt;User&gt; FindByName (string name)
    {
        // query code
    }

    public IList&lt;User&gt; FindByEmail (string email)
    {
        // query code
    }
}
</pre>
<p>Both <em>FindByName </em>and <em>FindByEmail </em>in <em>UserRepository </em>will in theory contain the same queries but with different parameters. However I don&#8217;t really want to have to write individual queries so I considered a utility method:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Repository &lt;TEntity&gt;
{
    public virtual TEntity FindById (object id)
    {
        ...
    }

    protected virtual IList&lt;TEntity&gt; FindByProperty (string propertyName, object value)
    {
        string columnName = NHibernateUtil.GetPropertyColumnName&lt;TEntity&gt; (propertyName);

        // Query here, e.g: &quot;SELECT .... WHERE .... columnName = value&quot; , etc.
    }
}

public class UserRepository : Repository&lt;User&gt;
{
    public IList&lt;User&gt; FindByName (string name)
    {
        return base.FindByProperty (&quot;Name&quot;, name);
    }

    public IList&lt;User&gt; FindByEmail (string email)
    {
        return base.FindByProperty (&quot;Email&quot;, email);
    }
}
</pre>
<p>Again this is very bad code and I hated the idea of it, so I sat down and started thinking. I remembered reading somewhere about C# 3.0 Expression Trees so I did some research. When using the special <em>Expression </em>type this seems to tell the compiler to create and expose an AST to us of e.g. a lambda function&#8217;s body, so if we pass a property reference expression we can parse the AST and extract the property name from there.</p>
<p>The theory in practice:</p>
<pre class="brush: csharp; title: ; notranslate">
public class UserRepository : Repository&lt;User&gt;
{
    public IList&lt;User&gt; FindByName (string name)
    {
        return base.FindByProperty (user =&gt; user.Name, name);
    }

    public IList&lt;User&gt; FindByEmail (string email)
    {
        return base.FindByProperty (user =&gt; user.Email, email);
    }
}

public class Repository &lt;TEntity&gt;
{
    public virtual TEntity FindById (object id)
    {
        ...
    }

    protected virtual IList&lt;TEntity&gt; FindByProperty (Expression&lt;Func&lt;TEntity, object&gt;&gt; propertyRefExpr,
                                                     object value)
    {
        string propertyName = GetPropertyName (propertyRefExpr);

        // Query code
    }

    private string GetPropertyName (Expression propertyRefExpr)
    {
        if (propertyRefExpr == null)
            throw new ArgumentNullException (&quot;propertyRefExpr&quot;, &quot;propertyRefExpr is null.&quot;);

        MemberExpression memberExpr = propertyRefExpr.Body as MemberExpression;
        if (memberExpr == null) {
            UnaryExpression unaryExpr = propertyRefExpr.Body as UnaryExpression;
            if (unaryExpr != null &amp;&amp; unaryExpr.NodeType == ExpressionType.Convert)
                memberExpr = unaryExpr.Operand as MemberExpression;
        }

        if (memberExpr != null &amp;&amp; memberExpr.Member.MemberType == MemberTypes.Property)
            return memberExpr.Member.Name;

        throw new ArgumentException (&quot;No property reference expression was found.&quot;,
                         &quot;propertyRefExpr&quot;);
    }
}
</pre>
<p>Also as a helper class:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class PropertyUtil
{
    public static string GetPropertyName&lt;TObject&gt; (this TObject type,
                                                   Expression&lt;Func&lt;TObject, object&gt;&gt; propertyRefExpr)
    {
        return GetPropertyNameCore (propertyRefExpr.Body);
    }

    public static string GetName&lt;TObject&gt; (Expression&lt;Func&lt;TObject, object&gt;&gt; propertyRefExpr)
    {
        return GetPropertyNameCore (propertyRefExpr.Body);
    }

    private static string GetPropertyNameCore (Expression propertyRefExpr)
    {
        if (propertyRefExpr == null)
            throw new ArgumentNullException (&quot;propertyRefExpr&quot;, &quot;propertyRefExpr is null.&quot;);

        MemberExpression memberExpr = propertyRefExpr as MemberExpression;
        if (memberExpr == null) {
            UnaryExpression unaryExpr = propertyRefExpr as UnaryExpression;
            if (unaryExpr != null &amp;&amp; unaryExpr.NodeType == ExpressionType.Convert)
                memberExpr = unaryExpr.Operand as MemberExpression;
        }

        if (memberExpr != null &amp;&amp; memberExpr.Member.MemberType == MemberTypes.Property)
            return memberExpr.Member.Name;

        throw new ArgumentException (&quot;No property reference expression was found.&quot;,
                         &quot;propertyRefExpr&quot;);
    }
}
</pre>
<p>As you can see it contains two generic methods that operate either on types:</p>
<pre class="brush: csharp; title: ; notranslate">
string propertyName = PropertyUtil.GetName&lt;User&gt; (u =&gt; u.Email);
</pre>
<p>or instances:</p>
<pre class="brush: csharp; title: ; notranslate">
User user = GetUser();
string propertyName = user.GetPropertyName (u =&gt; u.Email);
</pre>
<p>Great, isn&#8217;t it? And safe to refactor.</p>
<p>Of course there is no such thing as a free lunch and the use of expression trees comes at the expense of some performance.</p>
<p>BTW is the font size of the code snippets sufficiently readable or is it too tiny?</p>
<p><strong>UPDATE:</strong> Added support for Convert expressions (implicit/explicit casting)</p>
 <img src="http://ivanz.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=699" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://ivanz.com/2009/12/04/how-to-avoid-passing-property-names-as-strings-using-c-3-0-expression-trees/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>

