<?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>The Inquisitive Coder - Davy Brion&#039;s Blog &#187; NHibernate</title>
	<atom:link href="http://davybrion.com/blog/category/nhibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://davybrion.com/blog</link>
	<description>Trying to walk that thin line between intelligence and ignorance</description>
	<lastBuildDate>Wed, 17 Mar 2010 19:50:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using NHibernate In Your Service Layer</title>
		<link>http://davybrion.com/blog/2009/12/using-nhibernate-in-your-service-layer/</link>
		<comments>http://davybrion.com/blog/2009/12/using-nhibernate-in-your-service-layer/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 12:53:36 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=2036</guid>
		<description><![CDATA[I have an old post where i discuss how you can manage your NHibernate sessions in a service layer scenario.&#160; Now, the example of the service layer code in that post was pretty poor and people were asking for a better example.&#160; Hopefully, this post will do a better job at making sure everything is [...]]]></description>
			<content:encoded><![CDATA[<p>I have an old <a href="http://davybrion.com/blog/2008/06/managing-your-nhibernate-sessions/" target="_blank">post</a> where i discuss how you can manage your NHibernate sessions in a service layer scenario.&#160; Now, the example of the service layer code in that post was pretty poor and people were asking for a better example.&#160; Hopefully, this post will do a better job at making sure everything is clear <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>First of all, the idea is to make sure that managing the NHibernate session (creating it, starting a transaction, committing or rolling back the transaction and closing the session) is taken care of automatically so you no longer have to worry about it.&#160; I also want to avoid passing the NHibernate session around all the time.&#160; This means that it will be created automatically when a request is sent to your service layer and stored in some place that will keep the instance alive during the handling of the service layer request.&#160; Every class that needs a reference to the current session (ideally only classes that deal purely with data access) will be able to retrieve it very easily, all in a thread-safe manner that can never be influenced by other concurrent requests.</p>
<p>First of all, you need something to wrap NHibernate’s ISessionFactory.&#160; I use the ISessionProvider for that:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">ISessionProvider</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">ISession</span> Create();</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">SessionProvider</span> : <span style="color: #2b91af">ISessionProvider</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ISessionFactory</span> sessionFactory;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> SessionProvider(<span style="color: blue">string</span> mappingAssemblyName)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Configuration</span> configuration = <span style="color: blue">new</span> <span style="color: #2b91af">Configuration</span>()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddAssembly(mappingAssemblyName);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactory = configuration.BuildSessionFactory();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ISession</span> Create()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> sessionFactory.OpenSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>In my case, i configure the IOC container to pass the name of the assembly that contains the mappings to the constructor of the SessionProvider class.&#160; If you’re using this code directly in your application, you could just as well hardcode the name of the assembly here.</p>
<p>You’ll also need something that allows you to store and retrieve the NHibernate session for the duration of the current request.&#160; I use the IActiveSessionManager for that:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IActiveSessionManager</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">ISession</span> GetActiveSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">void</span> SetActiveSession(<span style="color: #2b91af">ISession</span> session);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">void</span> ClearActiveSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">bool</span> HasActiveSession { <span style="color: blue">get</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ActiveSessionManager</span> : <span style="color: #2b91af">IActiveSessionManager</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">const</span> <span style="color: blue">string</span> sessionKey = <span style="color: #a31515">&quot;_currentSession&quot;</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IRequestState</span> requestState;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> ActiveSessionManager(<span style="color: #2b91af">IRequestState</span> requestState)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.requestState = requestState;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ISession</span> GetActiveSession()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (Current == <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">&quot;There is no active ISession instance for this thread&quot;</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> Current;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> SetActiveSession(<span style="color: #2b91af">ISession</span> session)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (Current != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">&quot;There is already an active ISession instance for this thread&quot;</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Current = session;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> ClearActiveSession()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Current = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> HasActiveSession</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> Current != <span style="color: blue">null</span>; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: #2b91af">ISession</span> Current</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> requestState.Get&lt;<span style="color: #2b91af">ISession</span>&gt;(sessionKey);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">set</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; requestState.Store(sessionKey, <span style="color: blue">value</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>This class will store the ISession instance in the <a href="http://davybrion.com/blog/2009/01/abstracting-request-state/" target="_blank">current request state</a> (definitely click on that link if you don’t know IRequestState yet).</p>
<p>Now we can create our own Unit Of Work.&#160; This is not a pure Unit Of Work because it doesn’t do any change tracking or anything like that, but it does take care of creating an NHibernate session (which <em>does</em> do change tracking and anything that a real Unit Of Work should do) and cleaning it up when the Unit Of Work is completed.&#160; Here’s my implementation:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IUnitOfWork</span> : <span style="color: #2b91af">IDisposable</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">void</span> Clear();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">void</span> Flush();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">ITransaction</span> CreateTransaction();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">ITransaction</span> CreateTransaction(<span style="color: #2b91af">IsolationLevel</span> isolationLevel);</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UnitOfWork</span> : <span style="color: #2b91af">Disposable</span>, <span style="color: #2b91af">IUnitOfWork</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IActiveSessionManager</span> sessionManager;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ISession</span> session;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: blue">bool</span> isRootUnitOfWork;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> UnitOfWork(<span style="color: #2b91af">ISessionProvider</span> sessionProvider, <span style="color: #2b91af">IActiveSessionManager</span> sessionManager)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.sessionManager = sessionManager;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (sessionManager.HasActiveSession)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; isRootUnitOfWork = <span style="color: blue">false</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session = sessionManager.GetActiveSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">else</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; isRootUnitOfWork = <span style="color: blue">true</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session = sessionProvider.Create();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionManager.SetActiveSession(session);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Clear()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Clear();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Flush()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Flush();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ITransaction</span> CreateTransaction()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> CreateTransaction(<span style="color: #2b91af">IsolationLevel</span>.ReadCommitted);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ITransaction</span> CreateTransaction(<span style="color: #2b91af">IsolationLevel</span> isolationLevel)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (session.Transaction != <span style="color: blue">null</span> &amp;&amp; session.Transaction.IsActive)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">&quot;nested transactions are not supported!&quot;</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> session.BeginTransaction(isolationLevel);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> DisposeManagedResources()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (isRootUnitOfWork)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (session != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Close();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionManager.ClearActiveSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>The idea is very simple.&#160; When the Unit Of Work is created, it asks the IActiveSessionManager if there is already an active session available.&#160; If not, it will create a new session through the ISessionProvider, and store it as the active session through the IActiveSessionManager.&#160; In the old implementation, the Unit Of Work would automatically create a new session in the constructor, but this obviously causes problems if you want to reuse a certain request handler from another request handler if they both depend on a IUnitOfWork instance.&#160;&#160; The IUnitOfWork interface doesn’t expose a lot of functionality but it’s all you need to <em>manage</em> your session in your service layer.&#160; It gives you the ability to create a transaction, clear the session and flush the session.&#160; When the IUnitOfWork is disposed, it will clean up the session and instruct the IActiveSessionManager to get rid of the session for this request.&#160; </p>
<p>Once you have this, you have all you need to prepare your service layer to take care of NHibernate session management automatically.&#160; I’m going to base the following service layer code example on Agatha (just because i think it’s the easiest way to implement a service layer <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) but you can do exactly the same in your service layer.&#160; The important part is that you should configure your IOC container to inject a new instance of IUnitOfWork into the class that handles your service request.&#160; When the container injects the new instance, the NHibernate session will be created and stored in the IActiveSessionManager so there’s no more reason why you would have to do this yourself.</p>
<p>Now, i use the following class as the base class for all my request handlers that need NHibernate support:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">NhRequestHandler</span>&lt;TRequest, TResponse&gt; : <span style="color: #2b91af">RequestHandler</span>&lt;TRequest, TResponse&gt;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">where</span> TRequest : <span style="color: #2b91af">Request</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">where</span> TResponse : <span style="color: #2b91af">Response</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">IUnitOfWork</span> UnitOfWork { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> DisposeManagedResources()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (UnitOfWork != <span style="color: blue">null</span>) UnitOfWork.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">Response</span> Handle(<span style="color: #2b91af">Request</span> request)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">using</span> (<span style="color: #2b91af">ITransaction</span> transaction = UnitOfWork.CreateTransaction())</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Response</span> response;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">try</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; response = <span style="color: blue">base</span>.Handle(request);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; transaction.Commit();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">catch</span> (<span style="color: #2b91af">Exception</span> handlerException)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; transaction.Rollback();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> response;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>(Note: the real implementation contains a bit more logging but other than that this is the real thing)</p>
<p>If you don’t understand the whole request handling concept, please check out <a href="http://davybrion.com/blog/2009/11/requestresponse-service-layer-series/" target="_blank">the first 3 posts in this series</a>.&#160; Regardless of whether you’re using Agatha, your own Request/Response Service Layer or a classic (dare i say old-school?) service layer, the idea should be the same.&#160; Make sure this code is centralized in one place so you don’t have to repeat yourself all over your service layer code.&#160;&#160; Btw, in this case the IUnitOfWork instance is injected by the IOC container through Setter Injection instead of Constructor Injection.&#160; I’ve already discussed the reasons on why i prefer Setter Injection in this case <a href="http://davybrion.com/blog/2009/11/constructor-injection-vs-sette-injection/" target="_blank">here</a>.</p>
<p>Now, you’re going to have some classes that will need to use an ISession instance to perform their tasks.&#160; I always create Repository classes for that, but the following approach would be similar for any other type of class which needs an ISession.&#160;&#160; Call them Data Access Objects, Data Access Classes or Sloppy Joes for all i care.&#160;&#160; Whatever you call these classes, they need a dependency on the IActiveSessionManager.&#160;&#160; Simply declare the IActiveSessionManager to be a dependency of your Sloppy Joe, i mean, Repository or DAO or whatever, like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Repository</span>&lt;T&gt; : <span style="color: #2b91af">IRepository</span>&lt;T&gt;</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IActiveSessionManager</span> activeSessionManager;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> Repository(<span style="color: #2b91af">IActiveSessionManager</span> activeSessionManager)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.activeSessionManager = activeSessionManager;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: #2b91af">ISession</span> Session</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> activeSessionManager.GetActiveSession(); }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Now you can write request handlers like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">GetCustomersRequestHandler</span> : <span style="color: #2b91af">NhRequestHandler</span>&lt;<span style="color: #2b91af">GetCustomersRequest</span>, <span style="color: #2b91af">GetCustomersResponse</span>&gt;</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IRepository</span>&lt;<span style="color: #2b91af">Customer</span>&gt; repository;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> GetCustomersRequestHandler(<span style="color: #2b91af">IRepository</span>&lt;<span style="color: #2b91af">Customer</span>&gt; repository)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.repository = repository;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">Response</span> Handle(<span style="color: #2b91af">GetCustomersRequest</span> request)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> response = CreateTypedResponse();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; response.Customers = ConvertToDtos(repository.FindAll(request.Criteria));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> response;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">CustomerDto</span>[] ConvertToDtos(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Customer</span>&gt; customers)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// &#8230;</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Obviously, this is a simple example but it works just as well for complex request handlers.&#160; Your NHibernate session is created and cleaned up automatically, without you having to write that code every single time. Each request handler will run in a transaction, and it will be committed or rolled back automatically without you having to do anything for it.&#160; And you only need to access the ISession instance in your Sloppy Joes.</p>
<p>Also keep in mind that you can also use the the ISessionProvider, IActiveSessionManager and IUnitOfWork in a purely web-based scenario as well if you want to.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/12/using-nhibernate-in-your-service-layer/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Testing CRUD Operations With NHibernate</title>
		<link>http://davybrion.com/blog/2009/12/testing-crud-operations-with-nhibernate/</link>
		<comments>http://davybrion.com/blog/2009/12/testing-crud-operations-with-nhibernate/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 11:38:02 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=2015</guid>
		<description><![CDATA[I was asked to show how you can easily do CRUD tests, so here’s a base class that makes it very easy

&#160;&#160;&#160; public abstract class CrudTest&#60;TEntity, TId&#62; : NHibernateTest
&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TEntity : IHaveAnId&#60;TId&#62;
&#160;&#160;&#160; {
&#160;&#160;&#160;&#160;&#160;&#160;&#160; [Test]
&#160;&#160;&#160;&#160;&#160;&#160;&#160; public virtual void SelectQueryWorks()
&#160;&#160;&#160;&#160;&#160;&#160;&#160; {
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.CreateCriteria(typeof(TEntity)).SetMaxResults(5).List();
&#160;&#160;&#160;&#160;&#160;&#160;&#160; }
&#160;
&#160;&#160;&#160;&#160;&#160;&#160;&#160; [Test]
&#160;&#160;&#160;&#160;&#160;&#160;&#160; public virtual void AddEntity_EntityWasAdded()
&#160;&#160;&#160;&#160;&#160;&#160;&#160; {
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var entity = BuildEntity();
&#160;
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; InsertEntity(entity);
&#160;
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Evict(entity);
&#160;
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var [...]]]></description>
			<content:encoded><![CDATA[<p>I was <a href="http://davybrion.com/blog/2009/12/unit-testing-an-nhibernate-application/comment-page-1/#comment-23096" target="_blank">asked</a> to show how you can easily do CRUD tests, so here’s a base class that makes it very easy</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">CrudTest</span>&lt;TEntity, TId&gt; : <span style="color: #2b91af">NHibernateTest</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">where</span> TEntity : <span style="color: #2b91af">IHaveAnId</span>&lt;TId&gt;</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> SelectQueryWorks()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.CreateCriteria(<span style="color: blue">typeof</span>(TEntity)).SetMaxResults(5).List();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> AddEntity_EntityWasAdded()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> entity = BuildEntity();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; InsertEntity(entity);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Evict(entity);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> reloadedEntity = session.Get&lt;TEntity&gt;(entity.Id);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsNotNull(reloadedEntity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; AssertAreEqual(entity, reloadedEntity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; AssertValidId(reloadedEntity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> UpdateEntity_EntityWasUpdated()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> entity = BuildEntity();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; InsertEntity(entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ModifyEntity(entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; UpdateEntity(entity);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Evict(entity);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> reloadedEntity = session.Get&lt;TEntity&gt;(entity.Id);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsNotNull(reloadedEntity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; AssertAreEqual(entity, reloadedEntity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">Test</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> DeleteEntity_EntityWasDeleted()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> entity = BuildEntity();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; InsertEntity(entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DeleteEntity(entity);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.IsNull(session.Get&lt;TEntity&gt;(entity.Id));</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> InsertEntity(TEntity entity)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Save(entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Flush();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> UpdateEntity(TEntity entity)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Update(entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Flush();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> DeleteEntity(TEntity entity)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Delete(entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.Flush();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">abstract</span> TEntity BuildEntity();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">abstract</span> <span style="color: blue">void</span> ModifyEntity(TEntity entity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">abstract</span> <span style="color: blue">void</span> AssertAreEqual(TEntity expectedEntity, TEntity actualEntity);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">abstract</span> <span style="color: blue">void</span> AssertValidId(TEntity entity);</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Simply inherit from this class, implement the BuildEntity, ModifyEntity, AssertAreEqual and AssertValidId methods and that’s it.&#160; Those methods are usually pretty simple.&#160; In BuildEntity you just create an <em>unpersisted</em> entity and assign values to the properties, in ModifyEntity you modify the properties, and in AssertAreEqual you compare the properties of both instances.&#160; In AssertValidId, you make sure that the ID value is ok (depending on your identifier strategy).</p>
<p>This is good for regular CRUD operations, though we typically add extra tests when we want to test cascades or one-to-many associations mapped with inverse=”true”.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/12/testing-crud-operations-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Unit Testing An NHibernate Application</title>
		<link>http://davybrion.com/blog/2009/12/unit-testing-an-nhibernate-application/</link>
		<comments>http://davybrion.com/blog/2009/12/unit-testing-an-nhibernate-application/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 19:21:13 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=2008</guid>
		<description><![CDATA[
Grant Palin recently asked me for an in-depth article on TDD’ing an NHibernate application. While this post won’t be very in-depth, it might be helpful already.&#160; There are basically two approaches that i’ve seen used with good results, though there are obviously more approaches that you can use.&#160; I’m going to limit the scope of [...]]]></description>
			<content:encoded><![CDATA[</p>
<p><a href="http://grantpalin.com/blog/" target="_blank">Grant Palin</a> recently <a href="http://davybrion.com/blog/2009/11/400-posts/#comment-23070" target="_blank">asked me</a> for an in-depth article on TDD’ing an NHibernate application. While this post won’t be very in-depth, it might be helpful already.&#160; There are basically two approaches that i’ve seen used with good results, though there are obviously more approaches that you can use.&#160; I’m going to limit the scope of this post to the following two approaches though, and i’ll also discuss exactly what we test.</p>
<h5>Creating a new database for each test (or testfixture)</h5>
<p>This approach creates the database at the beginning of each test (or testfixture), runs the test (or tests in the fixture), and then destroys the database after the test (or testfixture) completed.&#160; The easiest way to do this is to create a base test class that all of you data access test class should inherit from.&#160; Here’s a simple example:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">NHibernateTest</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Configuration</span> configuration;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: #2b91af">ISessionFactory</span> sessionFactory;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">TestFixtureSetUp</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> TestFixtureSetup()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; configuration = <span style="color: blue">new</span> <span style="color: #2b91af">Configuration</span>()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddAssembly(<span style="color: #a31515">&quot;YourAssemblyName&quot;</span>);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">SchemaExport</span>(configuration).Create(<span style="color: blue">false</span>, <span style="color: blue">true</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; sessionFactory = configuration.BuildSessionFactory();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">TestFixtureTearDown</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> TestFixtureTearDown()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">SchemaExport</span>(configuration).Drop(<span style="color: blue">false</span>, <span style="color: blue">true</span>);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: #2b91af">ISession</span> CreateTransactionalSession()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> session = sessionFactory.OpenSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.BeginTransaction();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> session;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>This class will create the database from scratch once for each TestFixture, which means that each test in the fixture will use the same database.&#160; It also destroys the database at the end of the fixture.&#160; It creates the database based on your mappings, and as you can see, you really don’t have to do a lot for this.&#160; If you want the database to be recreated and dropped for each test, then you obviously need to move the code in the TestFixtureSetup and TestFixtureTearDown methods to your regular SetUp and TearDown methods.&#160; If you go that route, i’d advise you to include empty template methods before and after the setup and teardown so you can plug in some extra code before and after these operations in your derived test classes.</p>
<p>The biggest benefit of this approach is that you don’t have any possibly present state in the database that can influence your tests.&#160; The downside is that you can’t rely on certain data (eg reference data) to be present and you have to recreate it whenever you need it.&#160;&#160; You can also use multiple transactions in your tests, though you are also responsible for cleaning any data that is left in the database at the end of each test.&#160; You also need to guarantee that this always happens because any data that is left by one test might influence another one.&#160;&#160; Also, if you leave data in the database, that might lead to problems when dropping the database, so you really need to be careful with this. </p>
<p>Another problem with this example is that there is no automatic way to push the ISession instance to your data access components.&#160; That could easily be added though, depending on how your data access components retrieve a reference to a valid ISession.</p>
<h5>Tests that automatically roll back their transactions</h5>
<p>This is the approach that we always use at work.&#160; These tests require your database to be set up in a valid manner before your tests begin.&#160; Each test uses one transaction, which is automatically rolled back at the end of the test to prevent the possibility of any test data remaining in the database.&#160;&#160; With this way of testing, it’s also possible to provide some kind of ‘known state’ in the database (eg reference data) that you can use from within your code.</p>
<p>Here’s the NHibernateTest class that our NHibernate test classes all inherit from:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">NHibernateTest</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">static</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ActiveSessionManager</span> activeSessionManager = <span style="color: blue">new</span> <span style="color: #2b91af">ActiveSessionManager</span>();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">UnitOfWork</span> unitOfWork;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: #2b91af">ISession</span> session;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">abstract</span> <span style="color: #2b91af">ISessionProvider</span> GetSessionProvider();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: #2b91af">IActiveSessionManager</span> GetActiveSessionManager()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> activeSessionManager;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">SetUp</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> SetUp()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BeforeSetup();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> sessionManager = GetActiveSessionManager();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; unitOfWork = <span style="color: blue">new</span> <span style="color: #2b91af">UnitOfWork</span>(GetSessionProvider(), sessionManager);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session = sessionManager.GetActiveSession();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; unitOfWork.CreateTransaction();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; AfterSetup();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; [<span style="color: #2b91af">TearDown</span>]</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> TearDown()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BeforeTearDown();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (unitOfWork != <span style="color: blue">null</span>)</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; unitOfWork.Dispose();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; unitOfWork = <span style="color: blue">null</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; AfterTearDown();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> BeforeSetup() { }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> AfterSetup() { }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> BeforeTearDown() { }</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">virtual</span> <span style="color: blue">void</span> AfterTearDown() { }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
</p></div>
<p>&#160;</p>
<p>Now, this example uses our UnitOfWork and ActiveSessionManager classes (read <a href="http://davybrion.com/blog/2008/06/managing-your-nhibernate-sessions/" target="_blank">this</a> if you haven’t seen those yet) to make sure that our data access components can access the current ISession instance.&#160; Each test has a valid ISession present, which has already created a transaction and we can create/modify/delete data, run our queries, modify some stuff again, run our queries again and perform our assertions, all in the same transaction.&#160; After the test is completed, the transaction is never committed (and thus, automatically rolled back) so none of that data ever remains in the database.</p>
<h5></h5>
<h5>What Exactly Do We Test?</h5>
<p>Well, we test everything basically.&#160; We test all of our CRUD operations (again, with a simple base class which only requires you to implement the BuildEntity, ModifyEntity and AssertEqual methods and does all of the operations and checks automatically) for each entity.&#160; That’s right, <em>for each entity.</em>&#160; The extra work that this requires really doesn’t take a lot of time and it lets us know for a fact that our mappings are valid.</p>
<p>We also test every custom query that we write, always using the following approach: create some test data, flush the session, perform your query and verify that the expected data has indeed been returned by the query, and also that data that shouldn’t have been returned isn’t there.</p>
<p>And that’s pretty much it.&#160; We mock the data layer in all of our other tests, so our CRUD and query tests are the only ones that actually use NHibernate and the database.&#160; But CRUD actions and queries are tested very extensively.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/12/unit-testing-an-nhibernate-application/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Why NHibernate Entities Need A Public Or Protected Parameterless Constructor</title>
		<link>http://davybrion.com/blog/2009/10/why-nhibernate-entities-need-a-public-or-protected-parameterless-constructor/</link>
		<comments>http://davybrion.com/blog/2009/10/why-nhibernate-entities-need-a-public-or-protected-parameterless-constructor/#comments</comments>
		<pubDate>Sun, 04 Oct 2009 16:17:16 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1698</guid>
		<description><![CDATA[I have an older post where i discuss how you can implement a Value Object with NHibernate.  In that post i mentioned the following:
NHibernate allows a private default constructor for Value Objects, but for Entities you will need a default public or protected constructor as private is not sufficient.
I got the following comment from [...]]]></description>
			<content:encoded><![CDATA[<p>I have an older post where i discuss <a href="http://davybrion.com/blog/2009/03/implementing-a-value-object-with-nhibernate">how you can implement a Value Object with NHibernate</a>.  In that post i mentioned the following:</p>
<blockquote><p>NHibernate allows a private default constructor for Value Objects, but for Entities you will need a default public or protected constructor as private is not sufficient.</p></blockquote>
<p>I got the following comment from someone:</p>
<blockquote><p>
I too am trying to determine how well NHibernate lives up to the promise of persistence ignorance. I can definitely live with unnecessary private constructors, but I’m dubious about adding protected constructors just to support an ORM.</p>
<p>At any rate, I was surprised by the sentence I quoted, because I didn’t realize there were any circumstances in which NHibernate required protected default constructors.
</p></blockquote>
<p>Once again, the answer is related to the dynamic proxies that NHibernate uses.  Value Objects will never be proxied by NHibernate, so NHibernate only needs a private default constructor to create the instances.  If an entity is eligible for lazy loading however, then NHibernate will create a type which inherits from your entity (this is described in depth <a href="http://davybrion.com/blog/2009/03/must-everything-be-virtual-with-nhibernate/">here</a> and <a href="http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-iii/">here</a>).  Which means that we really need either a public or protected constructor in entity classes that are eligible for lazy loading.  Consider the following class:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">SomeEntity</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> SomeEntity(<span class="cb1">string</span> someRequiredValue)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> SomeEntity()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>If we try to create the following derived class:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">SomeEntityProxy</span> : <span class="cb2">SomeEntity</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>We get the following compiler error:</p>
<p>Error	1	&#8216;ConsoleApplication1.SomeEntity.SomeEntity()&#8217; is inaccessible due to its protection level	</p>
<p>It&#8217;s a silly example, but it does show why entity types need at least a public or a protected default constructor and why a private one isn&#8217;t sufficient.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/10/why-nhibernate-entities-need-a-public-or-protected-parameterless-constructor/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Must Everything Be Virtual With NHibernate, Part III</title>
		<link>http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-iii/</link>
		<comments>http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-iii/#comments</comments>
		<pubDate>Sun, 27 Sep 2009 17:45:30 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1686</guid>
		<description><![CDATA[In the previous post i showed a piece of code which suffers from 2 problems and asked you guys to spot both problems.  One of the problems was pointed out in the comments, but nobody mentioned the other one.
Once again, this is the code example:

Instead of making everything virtual, only properties that are eligible [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-ii/">previous post</a> i showed a piece of code which suffers from 2 problems and asked you guys to spot both problems.  One of the problems was pointed out in the comments, but nobody mentioned the other one.</p>
<p>Once again, this is the code example:</p>
<p><a href="http://davybrion.com/blog/wp-content/uploads/2009/09/transitive_persistence411.png"><img src="http://davybrion.com/blog/wp-content/uploads/2009/09/transitive_persistence411.png" alt="transitive_persistence41" title="transitive_persistence41" width="798" height="635" class="aligncenter size-full wp-image-1687" /></a></p>
<p>Instead of making everything virtual, only properties that are eligible for lazy-loading have been made virtual.  Now, the line of code that is problematic is obviously the one where the DiscountPercentage of the customer backing field is accessed.  I will address using the field instead of the property later on in this post so bear with me for now.</p>
<p>There are 2 situations in which this code will fail badly.  The first situation is when you&#8217;re dealing with a proxy of an Order.  If you have an uninitialized proxy of Order, and you call the non-virtual CreateOrderLine method then you will get a NullReferenceException because the proxy can&#8217;t intercept the call to CreateOrderLine, and because it also can&#8217;t intercept accessing the customer field, which will be null at that time.   This problem was correctly spotted by one of the people who left a comment.</p>
<p>The other problem is far worse, IMO.  Suppose you have a genuine instance of an Order object, but its reference properties haven&#8217;t been loaded yet and are uninitialized proxies.  If there is no requirement for every public member of a proxy-able type to be virtual, then we can pretty much assume that the DiscountPercentage of the Customer class is also non-virtual.  Which means that with this code, we have no possible way of intercepting the call to the Customer&#8217;s proxy&#8217;s DiscountPercentage property.  Unfortunately, DiscountPercentage will have its default value of 0, so you won&#8217;t get an exception&#8230; instead, the customer gets no discount even though its record in the database might have a discount set.</p>
<p>The possibility of running into one of these problems due to usage of an ORM and depending on how an object is loaded is simply unacceptable.  Some people commented on the usage of the customer backing field instead of the Customer property with a &#8220;then simply don&#8217;t do that&#8221; response.  That&#8217;s not an acceptable solution to this problem, it&#8217;s a lame workaround at best.  There are plenty of reasons why people would use the backing field in their code instead of the property and if they run into this problem, they definitely will blame the ORM.  And rightfully so, i might add.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-iii/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Must Everything Be Virtual With NHibernate, Part II</title>
		<link>http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-ii/</link>
		<comments>http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-ii/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 04:56:34 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1634</guid>
		<description><![CDATA[I already tried to explain this before, but here&#8217;s a simple example from a presentation i recently did on NHibernate:  

As you can see, only the properties of associations that are eligible for lazy-loading are virtual in this piece of code, because that is what many people seem to want.   There are [...]]]></description>
			<content:encoded><![CDATA[<p>I already tried to explain this <a href="http://davybrion.com/blog/2009/03/must-everything-be-virtual-with-nhibernate/">before</a>, but here&#8217;s a simple example from a presentation i recently did on NHibernate:  </p>
<p><img src="http://davybrion.com/blog/wp-content/uploads/2009/09/transitive_persistence41.png" alt="transitive_persistence4" title="transitive_persistence4" width="798" height="635" class="aligncenter size-full wp-image-1647" /></p>
<p>As you can see, only the properties of associations that are eligible for lazy-loading are virtual in this piece of code, because that is what many people seem to want.   There are actually 2 different ways in which this can cause problems&#8230;  can you spot both problems?</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/09/must-everything-be-virtual-with-nhibernate-part-ii/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Slides Of My NHibernate Talk</title>
		<link>http://davybrion.com/blog/2009/09/slides-of-my-nhibernate-talk/</link>
		<comments>http://davybrion.com/blog/2009/09/slides-of-my-nhibernate-talk/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 18:00:24 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1650</guid>
		<description><![CDATA[I&#8217;m giving a talk on NHibernate for the Belgian Visual Studio User Group right now (gotta love scheduled posts!).  You can download the slides of the presentation here.   I don&#8217;t like most typical technical presentations, so i wanted a slightly different approach.  So this presentation probably isn&#8217;t like most presentations that [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m giving a talk on NHibernate for the <a href="http://www.visug.be/">Belgian Visual Studio User Group</a> right now (gotta love scheduled posts!).  You can download the slides of the presentation <a href="http://davybrion.com/NHibernate.pptx">here</a>.   I don&#8217;t like most typical technical presentations, so i wanted a slightly different approach.  So this presentation probably isn&#8217;t like most presentations that you may be used to.  This is also the first time i&#8217;m giving a &#8216;big&#8217; talk for a group of people that i don&#8217;t know personally, so hopefully, it&#8217;ll be alright and i won&#8217;t screw up <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>If i did screw up: sorry, but at least it was free :p</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/09/slides-of-my-nhibernate-talk/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Of Course NHibernate Is Slow When You Use It Incorrectly</title>
		<link>http://davybrion.com/blog/2009/08/of-course-nhibernate-is-slow-when-you-use-it-incorrectly/</link>
		<comments>http://davybrion.com/blog/2009/08/of-course-nhibernate-is-slow-when-you-use-it-incorrectly/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 20:48:36 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1511</guid>
		<description><![CDATA[Just saw the following post where the performance of NHibernate and Entity Framework is compared for a couple of different operations.  Spoiler alert: NHibernate loses.  As it typically does in these kinds of &#8216;benchmarks&#8217; or &#8216;comparisons&#8217; that seem to pop up frequently lately.
For some reason, a lot of people seem to think that [...]]]></description>
			<content:encoded><![CDATA[<p>Just saw the following <a href="http://gregdoesit.com/2009/08/nhibernate-vs-entity-framework-a-performance-test/">post</a> where the performance of NHibernate and Entity Framework is compared for a couple of different operations.  Spoiler alert: NHibernate loses.  As it typically does in these kinds of &#8216;benchmarks&#8217; or &#8216;comparisons&#8217; that seem to pop up frequently lately.</p>
<p>For some reason, a lot of people seem to think that opening an NHibernate session and performing thousands of operations is a valid use case.  It&#8217;s not.  Far from it actually.  And with all of the features that NHibernate offers, it can&#8217;t possibly perform well in such a scenario.  See, an NHibernate session is a <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">unit of work</a>.  A unit of work is a business transaction which is typically short and small, but it should never be something huge.  Your DBA probably won&#8217;t appreciate huge database transactions on the database either.</p>
<p>Whenever you load an object through NHibernate, it will be tracked by the session that loaded it.  That means that the NHibernate session keeps a reference to it, and performs a series of checks on it periodically, depending on what you&#8217;re doing and some configuration settings such as the FlushMode.  For instance, suppose you&#8217;ve loaded a hundred different entities in one session.  If the FlushMode is set to automatic, it means that NHibernate will perform a dirty check for each entity associated with the session before each query is executed.  The more entity instances you&#8217;ve loaded, the longer this takes (obviously).  If you take this to an extreme level, like loading thousands of entities like most of these &#8216;benchmarks&#8217; do, performance will naturally be horrible.</p>
<p>Each entity instance is also stored in the first level (or session level) cache.  That means that whenever you retrieve a row from the database, NHibernate will check if an instance of that row already exists in the first level cache.  Again, the more instances you&#8217;ve loaded, the larger the overhead of this will be.   There are also a lot of possible extension points where you can plug in custom logic.  Again, there is a very minor cost that comes with this extensibility and as you can expect, that minor cost can add up to something much more noticable once you start dealing with an unreasonably large number of instances in your session.</p>
<p>Always keep in mind that an ORM (and this goes for every ORM) is most suitable for <a href="http://en.wikipedia.org/wiki/OLTP">OLTP</a>.  Using an ORM for batch processing jobs or large data processing operations in general is simply put a bad idea.  And they will never perform as well as other solutions in these scenarios.  So please don&#8217;t bother even benchmarking ORM performance in non OLTP usage because it quite simply doesn&#8217;t make sense to do so, and the results will be completely untrustworthy anyway.</p>
<p>An ORM can offer you nice performance gains in OLTP scenarios simply by trying to minimize database connectivity, minimizing the number of database operations, and relatively sane caching usage.  Unfortunately, these are aspects that are never tested in these &#8216;benchmarks&#8217; or &#8216;comparisons&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/08/of-course-nhibernate-is-slow-when-you-use-it-incorrectly/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>One Of My Favorite NHibernate 2.1 Features</title>
		<link>http://davybrion.com/blog/2009/07/one-of-my-favorite-nhibernate-2-1-features/</link>
		<comments>http://davybrion.com/blog/2009/07/one-of-my-favorite-nhibernate-2-1-features/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 09:38:16 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1464</guid>
		<description><![CDATA[Check out the following piece of code:


            Session.CreateQuery(
                @"delete from DocumentTypeAssignment
                  where [...]]]></description>
			<content:encoded><![CDATA[<p>Check out the following piece of code:</p>
<pre>
<code>
            Session.CreateQuery(
                @"delete from DocumentTypeAssignment
                  where Id.DmsDocument in (from DmsDocument where Id = :documentId) and
                        Id.DocumentType.Id not in (:newDocumentTypeIds)")
                .SetInt64("documentId", dmsDocumentId)
                .SetParameterList("newDocumentTypeIds", newDocumentTypesToAssign.ToList(), NHibernateUtil.Int64)
                .ExecuteUpdate();
</code>
</pre>
<p>(pay no attention to Id.DmsDocument or Id.DocumentType&#8230; it&#8217;s a composite key for a legacy table)</p>
<p>Which results in this SQL statement:</p>
<pre>
<code>
delete
    from
        DocumentManagement.DocumentTypeAssignment
    where
        (
            DmsDocumentID in (
                select
                    dmsdocumen1_.ID
                from
                    DocumentManagement.DmsDocument dmsdocumen1_
                where
                    dmsdocumen1_.ID=@p0
            )
        )
        and (
            DocumentTypeID not in  (
                @p1 , @p2
            )
        );
    @p0 = 1634, @p1 = 2313, @p2 = 2310
</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/07/one-of-my-favorite-nhibernate-2-1-features/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Avoid Using NHibernate With NUnit 2.4.6</title>
		<link>http://davybrion.com/blog/2009/06/avoid-using-nhibernate-with-nunit-2-4-6/</link>
		<comments>http://davybrion.com/blog/2009/06/avoid-using-nhibernate-with-nunit-2-4-6/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 17:35:42 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1432</guid>
		<description><![CDATA[We just spent about 2 hours trying to find out why our NHibernate tests were about 10x slower on our build server than they were on our local machines.  I had noticed lately that the build for one of our projects was taking longer and longer but i hadn&#8217;t really timed the difference.  [...]]]></description>
			<content:encoded><![CDATA[<p>We just spent about 2 hours trying to find out why our NHibernate tests were about 10x slower on our build server than they were on our local machines.  I had noticed lately that the build for one of our projects was taking longer and longer but i hadn&#8217;t really timed the difference.  This project has about 1200 tests that use NHibernate and they run in about 45-60 seconds on my local machine.  It turns out they took around 15 <strong>minutes</strong> on the buildserver when running them through TeamCity.</p>
<p>I logged into the buildserver and ran the tests manually using nunit&#8217;s console runner (with an NUnit-2.4.7 build that i happened to have installed somewhere on the machine) and they only took about 45 seconds.  After a lot of guesswork and screwing around, it turned out that we never modified our base build script (why yes, i do believe in build script inheritance) to use a newer version of NUnit.  We set up the buildserver about 1 year ago, and at that time, the latest stable NUnit version that TeamCity supported was NUnit 2.4.6.  Our base build script was still referring to NUnit 2.4.6, which apparently <a href="http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/nhibernate-nunit-2-4-6-and-log4net">sets log4net to use debug level logging</a>.  Now, NHibernate logs a huge amount of information at the debug level, so this turned out to slow down all of our builds that had NHibernate tests.</p>
<p>We changed the the 2.4.6 version in our script to 2.4.7 and the build time of this particular project decreased from around 50 minutes to about 35 minutes.  Yes, that&#8217;s still a lot but this is a huge project with a lot of legacy tests and the entire build process is pretty complex.  Other projects went from build times from around 7 minutes to about 2 minutes.</p>
<p>That&#8217;s a pretty nice improvement for simply changing a &#8220;6&#8243; to a &#8220;7&#8243; <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/06/avoid-using-nhibernate-with-nunit-2-4-6/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using The Guid.Comb Identifier Strategy</title>
		<link>http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy/</link>
		<comments>http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy/#comments</comments>
		<pubDate>Thu, 21 May 2009 12:00:31 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1238</guid>
		<description><![CDATA[As you may have read by now, it&#8217;s a good idea to avoid identity-style identifier strategies with ORM&#8217;s.  One of the better alternatives that i kinda like is the guid.comb strategy.  Using regular guids as a primary key value leads to fragmented indexes (due to the randomness of the guid&#8217;s value) which leads [...]]]></description>
			<content:encoded><![CDATA[<p>As you may have read by now, it&#8217;s a good idea to <a href="http://ayende.com/Blog/archive/2009/03/20/nhibernate-avoid-identity-generator-when-possible.aspx">avoid identity-style identifier strategies</a> with ORM&#8217;s.  One of the better alternatives that i kinda like is the guid.comb strategy.  Using regular guids as a primary key value leads to fragmented indexes (due to the randomness of the guid&#8217;s value) which leads to bad performance.  This is a problem that the guid.comb strategy can solve quite easily for you.</p>
<p>If you want to learn how the guid.comb strategy really works, be sure to check out <a href="http://www.informit.com/articles/article.aspx?p=25862">Jimmy Nilsson&#8217;s article on it</a>. Basically, this strategy generates sequential guids which solves the fragmented index issue.  You can generate these sequential guids in your database, but the downside of that is that your ORM would still need to insert each record seperately and fetch the generated primary key value each time.  NHibernate includes the guid.comb strategy which will generate the sequential guids before actually inserting the records in your database.</p>
<p>This obviously has some great benefits: </p>
<ul>
<li>you don&#8217;t have to hit the database immediately whenever a record needs to be inserted</li>
<li>you don&#8217;t need to retrieve a generated primary key value when a record was inserted</li>
<li>you can batch your insert statements</li>
</ul>
<p>Let&#8217;s see how we can use this with NHibernate.  First of all, you need to map the identifier of your entity like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #a31515; }
.cb3 { color: red; }
</style>
<div class="cf">
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">id</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Id</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">Id</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">guid</span>&quot;<span class="cb1"> &gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &nbsp; &lt;</span><span class="cb2">generator</span><span class="cb1"> </span><span class="cb3">class</span><span class="cb1">=</span>&quot;<span class="cb1">guid.comb</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;/</span><span class="cb2">id</span><span class="cb1">&gt;</span></p>
</div>
<p></code></p>
<p>And that&#8217;s actually all you have to do.  You don&#8217;t have to assign the primary key values or anything like that.  You don&#8217;t need to worry about them at all.  </p>
<p>Take a look at the following test:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: blue; }
.cb3 { color: #a31515; }
.cb4 { color: green; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span class="cb1">Test</span>]</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">public</span> <span class="cb2">void</span> InsertsAreOnlyExecutedAtTransactionCommit()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">var</span> insertCountBefore = sessionFactory.Statistics.EntityInsertCount;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">using</span> (<span class="cb2">var</span> session = sessionFactory.OpenSession())</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">using</span> (<span class="cb2">var</span> transaction = session.BeginTransaction())</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">for</span> (<span class="cb2">int</span> i = 0; i &lt; 50; i++)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">var</span> category = <span class="cb2">new</span> <span class="cb1">ProductCategory</span>(<span class="cb2">string</span>.Format(<span class="cb3">&quot;category {0}&quot;</span>, i + 1));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// at this point, the entity doesn't have an ID value yet</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreEqual(<span class="cb1">Guid</span>.Empty, category.Id);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; session.Save(category);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// now the entity has an ID value, but we still haven't hit the database yet</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreNotEqual(<span class="cb1">Guid</span>.Empty, category.Id);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// just verifying that we haven't hit the database yet to insert the new categories</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreEqual(insertCountBefore, sessionFactory.Statistics.EntityInsertCount);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; transaction.Commit();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// only now have the recors been inserted</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.AreEqual(insertCountBefore + 50, sessionFactory.Statistics.EntityInsertCount);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Interesting, no? The entities have an ID value after they have been &#8217;saved&#8217; by NHibernate.  But they haven&#8217;t actually been saved to the database yet though.  NHibernate always tries to wait as long as possible to hit the database, and in this case it only needs to hit the database when the transaction is committed.  If you&#8217;ve enabled <a href="http://davybrion.com/blog/2008/10/batching-nhibernates-dm-statements/">batching of DML statements</a>, you could severly reduce the number of times you need to hit the database in this scenario.</p>
<p>And in case you&#8217;re wondering, the generated guids look like this:</p>
<p>81cdb935-d371-4285-9dcb-9bdb0122f25f<br />
a44baf99-58e9-4ad7-9a59-9bdb0122f25f<br />
a88300c2-6d64-4ae3-a55b-9bdb0122f25f<br />
032c7884-da2f-4568-b505-9bdb0122f25f<br />
&#8230;.<br />
70d7713c-b38d-4341-953d-9bdb0122f25f</p>
<p>Notice the last part of the guids&#8230; this is what prevents the index fragmentation.</p>
<p>Obviously, this particular test is not a realistic scenario but i&#8217;m sure you understand how much of an improvement this identifier strategy could provide throughout an entire application.  The only downside (IMO) is that guid&#8217;s aren&#8217;t really human readable so if that is important to you, you should probably look into other identifier strategies.  The HiLo strategy would be particularly interesting in that case, but we&#8217;ll cover that in a later post <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Using SQL Functions in Criteria Restrictions</title>
		<link>http://davybrion.com/blog/2009/04/using-sql-functions-in-criteria-restrictions/</link>
		<comments>http://davybrion.com/blog/2009/04/using-sql-functions-in-criteria-restrictions/#comments</comments>
		<pubDate>Thu, 30 Apr 2009 11:31:53 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1348</guid>
		<description><![CDATA[A coworker needed to use a SQL function in the where clause of a query that he was creating with NHibernate&#8217;s ICriteria API.  Most examples of this on the web use HQL instead of the ICriteria API and since we primarily use the ICriteria API we looked into how to do this.
Turns out it [...]]]></description>
			<content:encoded><![CDATA[<p>A coworker needed to use a SQL function in the where clause of a query that he was creating with NHibernate&#8217;s ICriteria API.  Most examples of this on the web use HQL instead of the ICriteria API and since we primarily use the ICriteria API we looked into how to do this.</p>
<p>Turns out it is pretty simple to do, though the syntax isn&#8217;t really straightforward.  Suppose you want to query all of your employees who are born in a specific year.  You could mess around with some DateTime parameters, but most databases have SQL functions to get the year from a date.  Using the ICriteria API, this would look like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> employeesBornIn81 = session.CreateCriteria&lt;<span style="color: #2b91af;">Employee</span>&gt;()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .Add(<span style="color: #2b91af;">Restrictions</span>.Eq(<span style="color: #2b91af;">Projections</span>.SqlFunction(<span style="color: #a31515;">&quot;year&quot;</span>, <span style="color: #2b91af;">NHibernateUtil</span>.DateTime, <span style="color: #2b91af;">Projections</span>.Property(<span style="color: #a31515;">&quot;BirthDate&quot;</span>)), 1981))</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .List&lt;<span style="color: #2b91af;">Employee</span>&gt;();</p>
</div>
<p></code></p>
<p>which adds the following where clause to the SQL statement (on SQL Server 2005):</p>
<p>WHERE datepart(year, this_.BirthDate) = @p0;</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/using-sql-functions-in-criteria-restrictions/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>NHibernate&#8217;s Future Queries And Their Fallback Behavior</title>
		<link>http://davybrion.com/blog/2009/04/nhibernates-future-queries-and-their-fallback-behavior/</link>
		<comments>http://davybrion.com/blog/2009/04/nhibernates-future-queries-and-their-fallback-behavior/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 18:07:55 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1295</guid>
		<description><![CDATA[I&#8217;ve blogged about NHibernate&#8217;s Future queries a couple of times already.  But as you know, NHibernate aims to offer you a way to write your code completely independent of the actual database you&#8217;re using.  So what happens if you run your code, which is using the Future and FutureValue features, on a database [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve blogged about NHibernate&#8217;s Future queries a <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">couple</a> <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries-part-2/">of</a> <a href="http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/">times</a> already.  But as you know, NHibernate aims to offer you a way to write your code completely independent of the actual database you&#8217;re using.  So what happens if you run your code, which is using the Future and FutureValue features, on a database that doesn&#8217;t support batched queries?  Previously, this would fail with a NotSupportedException being thrown.</p>
<p>As of today, (revision 4177 if you want to be specific) this is no longer the case.  If you use the Future or FutureValue methods of either ICriteria or IQuery, and the database doesn&#8217;t support batching queries, NHibernate will fall back to simply executing the queries immediately, as the following tests show:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: blue; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span class="cb1">Test</span>]</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">public</span> <span class="cb2">void</span> FutureOfCriteriaFallsBackToListImplementationWhenQueryBatchingIsNotSupported()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">using</span> (<span class="cb2">var</span> session = sessions.OpenSession())</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">var</span> results = session.CreateCriteria&lt;<span class="cb1">Person</span>&gt;().Future&lt;<span class="cb1">Person</span>&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; results.GetEnumerator().MoveNext();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: blue; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; [<span class="cb1">Test</span>]</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">public</span> <span class="cb2">void</span> FutureValueOfCriteriaCanGetSingleEntityWhenQueryBatchingIsNotSupported()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">int</span> personId = CreatePerson();</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">using</span> (<span class="cb2">var</span> session = sessions.OpenSession())</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">var</span> futurePerson = session.CreateCriteria&lt;<span class="cb1">Person</span>&gt;()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .Add(<span class="cb1">Restrictions</span>.Eq(<span class="cb3">&quot;Id&quot;</span>, personId))</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .FutureValue&lt;<span class="cb1">Person</span>&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.IsNotNull(futurePerson.Value);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>There are more tests obviously, but you get the point.  The interesting part about these tests is how i disabled query batching support.  I only have Sql Server and MySQL running on this machine, and they both support query batching.  I didn&#8217;t really feel like installing a database that doesn&#8217;t support it, so i just took advantage of NHibernate&#8217;s extensibility.  Since most of us run the NHibernate tests on Sql Server, i inherited from the Sql Server Driver and made sure that it would report to NHibernate that it didn&#8217;t support query batching:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">TestDriverThatDoesntSupportQueryBatching</span> : <span class="cb2">SqlClientDriver</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">bool</span> SupportsMultipleQueries</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">get</span> { <span class="cb1">return</span> <span class="cb1">false</span>; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Easy huh? Then i just inherited from the TestCase class we have in the NHibernate.Tests project which offers a virtual method where you can modify the NHibernate configuration for the current fixture:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">protected</span> <span class="cb1">override</span> <span class="cb1">void</span> Configure(<span class="cb2">Configuration</span> configuration)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; configuration.Properties[<span class="cb2">Environment</span>.ConnectionDriver] = </p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb3">&quot;NHibernate.Test.NHSpecificTest.Futures.TestDriverThatDoesntSupportQueryBatching, NHibernate.Test&quot;</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">base</span>.Configure(configuration);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Now NHibernate thinks that query batching isn&#8217;t supported, yet the above tests still work.  Mission accomplished <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/nhibernates-future-queries-and-their-fallback-behavior/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Assigning Foreign Keys In NHibernate</title>
		<link>http://davybrion.com/blog/2009/04/assigning-foreign-keys-in-nhibernate/</link>
		<comments>http://davybrion.com/blog/2009/04/assigning-foreign-keys-in-nhibernate/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 05:46:52 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1206</guid>
		<description><![CDATA[This post from the Entity Framework team recently caught my attention.  It discusses the ability to add actual foreign key values to your entities instead of just references to the referred entities.  One of the benefits of this ability is that you can assign foreign key values to an entity&#8217;s properties without having [...]]]></description>
			<content:encoded><![CDATA[<p>This <a href="http://blogs.msdn.com/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx">post</a> from the Entity Framework team recently caught my attention.  It discusses the ability to add actual foreign key values to your entities instead of just references to the referred entities.  One of the benefits of this ability is that you can assign foreign key values to an entity&#8217;s properties without having to actually retrieve the entity you are referring to.  While i am no fan of this approach, i do want to point out that you can do this with NHibernate too, especially because some people don&#8217;t know about this.</p>
<p>Take a look at the following code:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; product.Category = session.Get&lt;<span class="cb1">ProductCategory</span>&gt;(categoryId);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; session.SaveOrUpdate(product);</p>
</div>
<p></code></p>
<p>This code changes the product&#8217;s Category property, and to do that it retrieves the actual ProductCategory instance through the id value of the category.  This causes 2 database hits.  One to retrieve the ProductCategory, and one to persist the Product.</p>
<p>You could do this instead:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: #2b91af; }
.cb2 { color: green; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; product.Category = session.Load&lt;<span class="cb1">ProductCategory</span>&gt;(categoryId);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">// this verifies that the product.Category is an uninitialized proxy</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">// which means that we did not fetch the product category from the database</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">Assert</span>.IsFalse(<span class="cb1">NHibernateUtil</span>.IsInitialized(product.Category));</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb2">// we were able to save the product without having loaded the product category</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; session.Save(product);</p>
</div>
<p></code></p>
<p>Notice how we use ISession&#8217;s Load method here, instead of the Get method to &#8216;retrieve&#8217; the ProductCategory.  The Get method actually fetches the entity from the database if it&#8217;s not already in the session cache.  The Load method however will return an uninitialized proxy to the ProductCategory entity if it&#8217;s not present in the session cache.  The NHibernateUtil.IsInitialized() method will return false, because this proxy is indeed uninitialized.  It does not hit the database until you try to access any of the properties of the ProductCategory proxy, except for its identifier property.  So accessing product.Category.Id would not hit the database, but product.Category.Name or product.Category.Description would.  </p>
<p>If you want to avoid hitting the database to assign foreign keys, using a proxy might be an interesting alternative for you. </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/assigning-foreign-keys-in-nhibernate/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Transparent Query Batching Through Your Repository</title>
		<link>http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/</link>
		<comments>http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 11:35:52 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1200</guid>
		<description><![CDATA[All of our projects that use NHibernate (which is all of them except those where the customer explicitly doesn&#8217;t want us to use it or where it wouldn&#8217;t make sense to use it) use the same Repository implementation.  After the Future and FutureValue queries were added to NHibernate, i modified the implementation of that [...]]]></description>
			<content:encoded><![CDATA[<p>All of our projects that use NHibernate (which is all of them except those where the customer explicitly doesn&#8217;t want us to use it or where it wouldn&#8217;t make sense to use it) use the same <a href="http://davybrion.com/blog/2008/06/data-access-with-nhibernate/">Repository implementation</a>.  After the <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries/">Future</a> and <a href="http://davybrion.com/blog/2009/01/nhibernate-and-future-queries-part-2/">FutureValue</a> queries were added to NHibernate, i modified the implementation of that Repository class.  </p>
<p>Two of the FindAll methods now look like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IEnumerable</span>&lt;T&gt; FindAll()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> Session.CreateCriteria&lt;T&gt;().Future&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IEnumerable</span>&lt;T&gt; FindAll(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).Future&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>The only thing i changed in those methods is calling the Future method, instead of the List method.  That&#8217;s it.  All of our specific Find-methods (those that execute specific queries) pass through the FindAll(DetachedCriteria criteria) method so they all benefit from this change.  </p>
<p>That means that all of our queries are suddenly batched transparently whenever possible, without impacting any of the calling code.  And that is pretty nice if you ask me.  Batching queries can offer a substantial performance benefit, and we didn&#8217;t even have to change any of the calling code to achieve it.  </p>
<p>Obviously, this only works for the queries that return IEnumerables (in our case, that&#8217;s every query that doesn&#8217;t return a single value).  I also added a few more methods to enable query batching for queries that return a single entity, or a scalar value (i kept the original methods in this code snippet as well so you can see the difference):</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> T FindOne(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).UniqueResult&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IFutureValue</span>&lt;T&gt; FindFutureOne(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).FutureValue&lt;T&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
</div>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> K GetScalar&lt;K&gt;(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> (K)criteria.GetExecutableCriteria(Session).UniqueResult();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IFutureValue</span>&lt;K&gt; GetFutureScalar&lt;K&gt;(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> criteria.GetExecutableCriteria(Session).FutureValue&lt;K&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
</div>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">int</span> Count(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> <span class="cb2">Convert</span>.ToInt32(QueryCount(criteria).GetExecutableCriteria(Session).UniqueResult());</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">IFutureValue</span>&lt;<span class="cb1">int</span>&gt; FutureCount(<span class="cb2">DetachedCriteria</span> criteria)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> QueryCount(criteria).GetExecutableCriteria(Session).FutureValue&lt;<span class="cb1">int</span>&gt;();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
</div>
<p></code></p>
<p>So let&#8217;s recap.  Queries that return IEnumerables are all batched transparently whenever it&#8217;s possible to do so.  No calling code had to be modified to get this benefit.  Queries that return single values (an entity instance or a scalar value) that still use the &#8216;old&#8217; FindOne, GetScalar and Count methods obviously couldn&#8217;t benefit from the transparent batching without breaking backwards compatibility, but the new methods that were introduced do enable transparent batching for these queries from now on.</p>
<p>Does all of this sound too good to be true? I&#8217;d be skeptic too if i were you but i made these changes a few months ago actually and we have been using this stuff on a couple of projects with zero problems.  </p>
<p>Obviously, you need NHibernate 2.1 Alpha 1 (or later) for this or the current trunk, both of which i would recommend over NH 2.0 at this point.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/04/transparent-query-batching-through-your-repository/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Must Everything Be Virtual With NHibernate?</title>
		<link>http://davybrion.com/blog/2009/03/must-everything-be-virtual-with-nhibernate/</link>
		<comments>http://davybrion.com/blog/2009/03/must-everything-be-virtual-with-nhibernate/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 20:05:11 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1210</guid>
		<description><![CDATA[If you&#8217;ve ever used NHibernate 2.0 or later, you will have undoubtedly run into the following runtime exception a couple of times:
NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:
NHibernateExamples.Entities.OrderLine: method get_UnitPrice should be &#8216;public/protected virtual&#8217; or &#8216;protected internal virtual&#8217;
NHibernateExamples.Entities.OrderLine: method set_UnitPrice should be &#8216;public/protected virtual&#8217; or &#8216;protected internal virtual&#8217;
Oops&#8230; we forgot to make [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve ever used NHibernate 2.0 or later, you will have undoubtedly run into the following runtime exception a couple of times:</p>
<p>NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:<br />
NHibernateExamples.Entities.OrderLine: method get_UnitPrice should be &#8216;public/protected virtual&#8217; or &#8216;protected internal virtual&#8217;<br />
NHibernateExamples.Entities.OrderLine: method set_UnitPrice should be &#8216;public/protected virtual&#8217; or &#8216;protected internal virtual&#8217;</p>
<p>Oops&#8230; we forgot to make the UnitPrice property on the OrderLine entity virtual.  But why does it need to be virtual in the first place? That&#8217;s a question that many people who are new to NHibernate have.</p>
<p>The quick answer to that question is: because we need members to be virtual in order to do our lazy loading magic/voodoo.</p>
<p>The longer answer is more interesting though.  An important feature that any real ORM must have is transparent Lazy Loading.  If you retrieve an object through an ORM, you don&#8217;t want it to automatically pull in an entire object graph (not by default anyway), yet you don&#8217;t want to litter your code with checks to see if certain associations have been loaded yet, and then loading them if necessary.  This is the ORM&#8217;s responsibility.  Ideally, you want to be able to access properties and have the ORM load the necessary data upon first access of those properties if the data hasn&#8217;t been retrieved yet.</p>
<p>NHibernate has this ability, yet it doesn&#8217;t require you to inherit from some kind of NHibernate base class or implement any interfaces or anything like that. So how does it work? Well, NHibernate uses proxies of your classes at runtime whenever lazy loading is required.  Ok, so what exactly is a proxy? In this case, an NHibernate proxy is a type which is generated dynamically when NHibernate is initialized for your application (this only happens once upon application startup).  A proxy type will be generated for each of your entities that hasn&#8217;t explicitly been mapped to avoid lazy loading (more on this later).  A proxy type for one of your entities will actually <strong>inherit</strong> from your entity, and will then intercept each possible call you can perform on that type. </p>
<p>Let&#8217;s discuss a small example that might make things clearer.  Suppose you have an Order class.  The Order class has properties such as Employee and Customer, among others.  But when you load Order instances, you might not always want the Employee property to already contain the real Employee entity instance.  Same thing goes for the Customer property.  By default, NHibernate considers each entity type as eligible for lazy loading unless it&#8217;s been explicitly configured not to (again, more on this later).  So when NHibernate is initialized, it will know that it needs to dynamically generate proxy types for Customer and Employee.  Let&#8217;s just assume these types will be named CustomerProxyType and EmployeeProxyType (they wouldn&#8217;t be called like that btw, but it doesn&#8217;t matter). Now suppose that you are retrieving an Order instance (or a bunch of them, doesn&#8217;t really matter) and you don&#8217;t instruct NHibernate to already fetch the Customer or Employee data.  You haven&#8217;t requested the Customer or Employee data, so it shouldn&#8217;t be there, right?  But it shouldn&#8217;t be null either, right?  So NHibernate assigns an instance of the CustomerProxyType class to the Customer property, and an instance of EmployeeProxyType and initializes both proxies so that they contain their identifier value, which you already have in memory anyway after selecting the order record.</p>
<p>You can safely use the Order instance(s) and you can even access the Employee and Customer instances and nothing will happen.  But, whenever you access any of the non-identifier members (that means properties _and_ methods) of a proxy instance, NHibernate needs to make sure that the data of either the Customer or the Employee (depending on which one you&#8217;re using) needs to be fetched from the database.  So how does NHibernate do that?  The proxies will <strong>override</strong> all of your properties and methods and when one of them is accessed, NHibernate will either fetch the data of the entity if it&#8217;s not present yet and then proceed with the original implementation of the property or the method, or it will immediately call the original implementation if the data was already present.</p>
<p>This is basic OO&#8230; your entities are base classes to NHibernate&#8217;s proxies, and those proxies need to add a little bit of behavior to your entities&#8217; behavior.  In order to do that, NHibernate needs to override every public member to make sure that this extra behavior is triggered at the appropriate time.  Now, there are quite a few people who dislike this requirement.  First of all, there is a minor performance cost to calling virtual members as opposed to calling non virtual members.  However, this performance cost is really extremely small and in practically every situation it&#8217;s completely negligible.  This extra cost certainly doesn&#8217;t even compare to some real world performance costs, like hitting the database more often than you should or retrieving more data than you really need.  Another reason why some people don&#8217;t like this is because they don&#8217;t like to enable derived classes to override whatever member they want to.  In some cases, this is a valid objection.  In most cases however, it&#8217;s pure Intellectual Masturbation which offers no real value at all.  There are other ORM&#8217;s that don&#8217;t require you to make your members virtual and they are still able to offer lazy loading features.  But those ORM&#8217;s usually require you to either inherit from a specified base class, or to implement one or more interfaces that the ORM will use.  In both cases, i&#8217;d argue that this pollutes your entities far more than virtual members do, but that&#8217;s just my opinion.</p>
<p>But for those cases where you really do not want to make members virtual, and don&#8217;t mind forgoing on the lazy-loading features of NHibernate, you can simply map those entities to not enable lazy loading at all.  You could just map an entity like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #a31515; }
.cb3 { color: red; }
</style>
<div class="cf">
<p class="cl"><span class="cb1">&nbsp; &lt;</span><span class="cb2">class</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">OrderLine</span>&quot;<span class="cb1"> </span><span class="cb3">table</span><span class="cb1">=</span>&quot;<span class="cb1">OrderLine</span>&quot;<span class="cb1"> </span><span class="cb3">lazy</span><span class="cb1">=</span>&quot;<span class="cb1">false</span>&quot;<span class="cb1"> &gt;</span></p>
</div>
<p></code></p>
<p>Setting the lazy attribute to false will ensure that NHibernate will not create a proxy type of your entity type, and that you will always be dealing with instances of the actual type of your entity instead of a possible proxy type.  It also means that you will never be able to use any kind of lazy loading when it comes to retrieving instances of these entity types. </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/03/must-everything-be-virtual-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Avoiding MySQL&#8217;s MAX_JOIN_SIZE Limit With NHibernate</title>
		<link>http://davybrion.com/blog/2009/03/avoiding-mysqls-max_join_size-limit-with-nhibernate/</link>
		<comments>http://davybrion.com/blog/2009/03/avoiding-mysqls-max_join_size-limit-with-nhibernate/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 11:26:51 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1245</guid>
		<description><![CDATA[We&#8217;re working on an application which has to use a legacy MySQL database.  So far, we haven&#8217;t really had any problems with MySQL (apart from the dreadful legacy schema but that&#8217;s another issue) but today, i started getting an exception with the following message:
The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re working on an application which has to use a legacy MySQL database.  So far, we haven&#8217;t really had any problems with MySQL (apart from the dreadful legacy schema but that&#8217;s another issue) but today, i started getting an exception with the following message:</p>
<p>The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET SQL_MAX_JOIN_SIZE=# if the SELECT is okay</p>
<p>There is a certain complex view in our application which apparently hits this default limit set by MySQL once there is a certain amount of data present.  The view itself is a costly one&#8230; it really does need to do a whole lot of joins and rewriting it to use less joins would probably take a long time.</p>
<p>So i figured the better option in this case would be to set the SQL_BIG_SELECTS option to 1.  The only problem was: how? It&#8217;s not a setting that you can pass through the connection string (or at least, i did not find a way to do so) and NHibernate is taking care of all of the database communication.</p>
<p>I remembered a trick i had used <a href="http://davybrion.com/blog/2008/09/extending-nhibernates-driverconnectionprovider/">earlier</a>, which is to extend NHibernate&#8217;s DriverConnectionProvider.  It could then set the setting with the appropriate value whenever the connection is opened, like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">CustomConnectionProvider</span> : NHibernate.Connection.DriverConnectionProvider</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: #2b91af;">IDbConnection</span> GetConnection()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">IDbConnection</span> connection = <span style="color: blue;">base</span>.GetConnection();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; EnableBigSelects(connection);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> connection;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">void</span> EnableBigSelects(<span style="color: #2b91af;">IDbConnection</span> connection)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> command = connection.CreateCommand())</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; command.CommandText = <span style="color: #a31515;">&quot;SET SQL_BIG_SELECTS=1&quot;</span>;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; command.ExecuteNonQuery();</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>After that, you just set the DriverConnectionProvider to use in your hibernate.cfg.xml file like this:</p>
<p><code></p>
<div style="font-family: Consolas; font-size: 9pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">property</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>&quot;<span style="color: blue;">connection.provider</span>&quot;<span style="color: blue;">&gt;</span>MyProject.Infrastructure.NHibernate.CustomConnectionProvider, MyProject<span style="color: blue;">&lt;/</span><span style="color: #a31515;">property</span><span style="color: blue;">&gt;</span></p>
</div>
<p></code></p>
<p>And all is well.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/03/avoiding-mysqls-max_join_size-limit-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implementing A Value Object With NHibernate</title>
		<link>http://davybrion.com/blog/2009/03/implementing-a-value-object-with-nhibernate/</link>
		<comments>http://davybrion.com/blog/2009/03/implementing-a-value-object-with-nhibernate/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 22:12:06 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1174</guid>
		<description><![CDATA[I&#8217;ve covered implementing a Value Object before, but this post is about using Value Objects with NHibernate.  First, a little recap of what a Value Object is for those who don&#8217;t know yet.
A Value Object (also known as Immutable Object) is basically an object without a conceptual identity. A Value Object is defined through [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve covered <a href="http://davybrion.com/blog/2007/07/implementing-a-value-object/">implementing a Value Object</a> before, but this post is about using Value Objects with NHibernate.  First, a little recap of what a Value Object is for those who don&#8217;t know yet.</p>
<p>A Value Object (also known as Immutable Object) is basically an object without a conceptual identity. A Value Object is defined through its inner values, and not an identity like Entities. This means that a Value Object’s inner values can not be changed after object creation, hence the term Immutable Object. Should you need to change the inner values of the Value Object, you should actually create a new Value Object.</p>
<p>For some of you, this might seem odd. But you’ve actually used Value Objects on many occasions already. In .NET, strings are Value Objects. So are DateTime instances. If you create a string, you can’t modify its inner value. If you do, a new string is actually created. Same thing with a DateTime. The DateTime class provides methods to add days, hours, seconds, whatever… but those methods never modify the instance’s inner value. Instead, they return a new DateTime object because each DateTime instance is immutable.</p>
<p>This has interesting consequences on object equality. Two Value Objects holding the same data should be considered identical objects, even though they are 2 different instances.  A Value Object should therefore properly implement the Equals and GetHashCode methods.</p>
<p>For this example, we&#8217;ll define a Name class, which is a Value Object consisting of 2 values: FirstName and LastName.  If 2 people have the same first and last name, you could say that they have the same &#8216;name&#8217;, right? We&#8217;ll just ignore middle names here&#8230;  The combination of a FirstName and LastName would make for a good Value Object.  We need to make sure that once an instance of the Name class has been created, none of its values can be modified.  We also need to make sure that multiple instances of the Name class that have the same values can be safely considered equal to each other.  The code of the Name class looks like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: green; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">Name</span> : <span class="cb2">IEquatable</span>&lt;<span class="cb2">Name</span>&gt;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">readonly</span> <span class="cb1">string</span> firstName;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">readonly</span> <span class="cb1">string</span> lastName;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> Name(<span class="cb1">string</span> firstName, <span class="cb1">string</span> lastName)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.firstName = firstName;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.lastName = lastName;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb3">// the default constructor is only here for NH (private is sufficient, it doesn't need to be public)</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> Name() : <span class="cb1">this</span>(<span class="cb1">string</span>.Empty, <span class="cb1">string</span>.Empty) {}</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">string</span> LastName</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">get</span> { <span class="cb1">return</span> lastName; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">string</span> FirstName</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">get</span> { <span class="cb1">return</span> firstName; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">bool</span> Equals(<span class="cb2">Name</span> other)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (ReferenceEquals(<span class="cb1">null</span>, other)) <span class="cb1">return</span> <span class="cb1">false</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (ReferenceEquals(<span class="cb1">this</span>, other)) <span class="cb1">return</span> <span class="cb1">true</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> Equals(other.firstName, firstName) &amp;&amp; Equals(other.lastName, lastName);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">bool</span> Equals(<span class="cb1">object</span> obj)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (ReferenceEquals(<span class="cb1">null</span>, obj)) <span class="cb1">return</span> <span class="cb1">false</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (ReferenceEquals(<span class="cb1">this</span>, obj)) <span class="cb1">return</span> <span class="cb1">true</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (obj.GetType() != <span class="cb1">typeof</span>(<span class="cb2">Name</span>)) <span class="cb1">return</span> <span class="cb1">false</span>;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> Equals((<span class="cb2">Name</span>)obj);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">override</span> <span class="cb1">int</span> GetHashCode()</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">unchecked</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> (firstName.GetHashCode() * 397) ^ lastName.GetHashCode();</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">static</span> <span class="cb1">bool</span> <span class="cb1">operator</span> ==(<span class="cb2">Name</span> left, <span class="cb2">Name</span> right)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> Equals(left, right);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">static</span> <span class="cb1">bool</span> <span class="cb1">operator</span> !=(<span class="cb2">Name</span> left, <span class="cb2">Name</span> right)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">return</span> !Equals(left, right);</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>Take a close look at the constructors.  The public constructor takes both required values (firstName and lastName), and assigns them to the private fields.  The default constructor (which we&#8217;ve made private) merely calls the public constructor and passes String.Empty to the public constructor&#8217;s parameters.  As you can gather from the comments on the private constructor, it&#8217;s only reason for existence is because NHibernate requires classes to have a default constructor.  Well actually, that&#8217;s not entirely accurate since it is possible to use classes without a default constructor but it&#8217;s not trivial do so. </p>
<p>Creating a private default constructor seems to be a reasonable alternative.  Developers can&#8217;t create invalid Name instances (unless they cheat with reflection), and NHibernate can use the private constructor so it can create the instances before it fills the fields with the values from the database.  </p>
<p>Note: NHibernate allows a private default constructor for Value Objects, but for Entities you will need a default public or protected constructor as private is not sufficient.</p>
<p>We can now use this Value Object in every entity we want by simply adding a property to the entity like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">Name</span> Name { <span class="cb1">get</span>; <span class="cb1">set</span>; }</p>
</div>
<p></code></p>
<p>The mapping of the Value Object must be added to the mapping of the entity like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #a31515; }
.cb3 { color: red; }
</style>
<div class="cf">
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">component</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Name</span>&quot;<span class="cb1"> </span><span class="cb3">class</span><span class="cb1">=</span>&quot;<span class="cb1">NHibernateExamples.Values.Name</span>&quot;<span class="cb1"> </span><span class="cb3">insert</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> </span><span class="cb3">update</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1">&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &nbsp; &lt;</span><span class="cb2">property</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">FirstName</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">FirstName</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">string</span>&quot;<span class="cb1"> </span><span class="cb3">length</span><span class="cb1">=</span>&quot;<span class="cb1">50</span>&quot;<span class="cb1"> </span><span class="cb3">not-null</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> </span><span class="cb3">access</span><span class="cb1">=</span>&quot;<span class="cb1">nosetter.camelcase</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &nbsp; &lt;</span><span class="cb2">property</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">LastName</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">LastName</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">string</span>&quot;<span class="cb1"> </span><span class="cb3">length</span><span class="cb1">=</span>&quot;<span class="cb1">50</span>&quot;<span class="cb1"> </span><span class="cb3">not-null</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> </span><span class="cb3">access</span><span class="cb1">=</span>&quot;<span class="cb1">nosetter.camelcase</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;/</span><span class="cb2">component</span><span class="cb1">&gt;</span></p>
</div>
<p></code></p>
<p>Notice the value of the access attribute.  It&#8217;s set to nosetter.camelcase.  That means that NHibernate will use the get property when reading the values, but it will use a camelcase private field to set the values when it&#8217;s creating the object with values from the database.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/03/implementing-a-value-object-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Entities: Required Properties And Properties That Shouldn&#8217;t Be Modified</title>
		<link>http://davybrion.com/blog/2009/03/entities-required-properties-and-properties-that-shouldnt-be-modified/</link>
		<comments>http://davybrion.com/blog/2009/03/entities-required-properties-and-properties-that-shouldnt-be-modified/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 19:48:26 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1182</guid>
		<description><![CDATA[How often do you see entities mapped with getters and setters for every property, and only a default constructor (either added implicitly by the compiler or explicitly by a developer)?  It&#8217;s not really the best way to map entities, so i just wanted to show a better way of doing this.
Consider the OrderLine entity. [...]]]></description>
			<content:encoded><![CDATA[<p>How often do you see entities mapped with getters and setters for every property, and only a default constructor (either added implicitly by the compiler or explicitly by a developer)?  It&#8217;s not really the best way to map entities, so i just wanted to show a better way of doing this.</p>
<p>Consider the OrderLine entity.  It has 4 required properties: Order, Product, UnitPrice and Quantity.  It also has one optional property called DiscountPercentage.  The Order and Product properties should never be changed after the OrderLine was created.  It also has a database Id property which should never be changed either.</p>
<p> This is how the code of the OrderLine class would look like:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #2b91af; }
.cb3 { color: #a31515; }
.cb4 { color: green; }
</style>
<div class="cf">
<p class="cl">&nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">class</span> <span class="cb2">OrderLine</span> : <span class="cb2">IIdentifiable</span>&lt;<span class="cb1">int</span>&gt;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> OrderLine(<span class="cb2">Order</span> order, <span class="cb2">Product</span> product, <span class="cb1">decimal</span> unitPrice, <span class="cb1">int</span> quantity)</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (order == <span class="cb1">null</span>) <span class="cb1">throw</span> <span class="cb1">new</span> <span class="cb2">ArgumentNullException</span>(<span class="cb3">&quot;order&quot;</span>); </p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">if</span> (product == <span class="cb1">null</span>) <span class="cb1">throw</span> <span class="cb1">new</span> <span class="cb2">ArgumentNullException</span>(<span class="cb3">&quot;product&quot;</span>);</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.order = order;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">this</span>.product = product;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; UnitPrice = unitPrice;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Quantity = quantity;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb4">// required for NH</span></p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">protected</span> OrderLine() {}</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb1">int</span> id;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">int</span> Id</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">get</span> { <span class="cb1">return</span> id; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb2">Order</span> order;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">Order</span> Order</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">get</span> { <span class="cb1">return</span> order; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">private</span> <span class="cb2">Product</span> product;</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb2">Product</span> Product</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">get</span> { <span class="cb1">return</span> product; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p class="cl">&nbsp;</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">decimal</span> UnitPrice { <span class="cb1">get</span>; <span class="cb1">set</span>; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">int</span> Quantity { <span class="cb1">get</span>; <span class="cb1">set</span>; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span class="cb1">public</span> <span class="cb1">virtual</span> <span class="cb1">double</span>? DiscountPercentage { <span class="cb1">get</span>; <span class="cb1">set</span>; }</p>
<p class="cl">&nbsp;&nbsp;&nbsp; }</p>
</div>
<p></code></p>
<p>There is only one public constructor, which takes all of the required properties as parameters.  The protected constructor is only there because NHibernate needs it to create run-time proxies (which enable all of the lazy-loading magic).  In theory, you can&#8217;t create instances of the OrderLine entity without its required data.</p>
<p>Also, notice how the Id, Order and Product properties only have a getter, and no setter.  These values can no longer be changed by developers once the object is constructed.  The UnitPrice and Quantity properties do have setters, because these values can be modified after the entity is created.</p>
<p>The mapping for this class looks like this:</p>
<p><code></p>
<style type="text/css">
.cf { font-family: Consolas; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: blue; }
.cb2 { color: #a31515; }
.cb3 { color: red; }
</style>
<div class="cf">
<p class="cl"><span class="cb1">&nbsp; &lt;</span><span class="cb2">class</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">OrderLine</span>&quot;<span class="cb1"> </span><span class="cb3">table</span><span class="cb1">=</span>&quot;<span class="cb1">OrderLine</span>&quot;<span class="cb1"> &gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">id</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Id</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">Id</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">int</span>&quot;<span class="cb1"> </span><span class="cb3">access</span><span class="cb1">=</span>&quot;<span class="cb1">nosetter.camelcase</span>&quot;<span class="cb1"> &gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &nbsp; &lt;</span><span class="cb2">generator</span><span class="cb1"> </span><span class="cb3">class</span><span class="cb1">=</span>&quot;<span class="cb1">identity</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;/</span><span class="cb2">id</span><span class="cb1">&gt;</span></p>
<p class="cl">&nbsp;</p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">many-to-one</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Order</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">OrderId</span>&quot;<span class="cb1"> </span><span class="cb3">class</span><span class="cb1">=</span>&quot;<span class="cb1">Order</span>&quot;<span class="cb1"> </span><span class="cb3">not-null</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> </span><span class="cb3">access</span><span class="cb1">=</span>&quot;<span class="cb1">nosetter.camelcase</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">many-to-one</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Product</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">ProductId</span>&quot;<span class="cb1"> </span><span class="cb3">class</span><span class="cb1">=</span>&quot;<span class="cb1">Product</span>&quot;<span class="cb1"> </span><span class="cb3">not-null</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> </span><span class="cb3">access</span><span class="cb1">=</span>&quot;<span class="cb1">nosetter.camelcase</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">property</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">UnitPrice</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">UnitPrice</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">Decimal</span>&quot;<span class="cb1"> </span><span class="cb3">not-null</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">property</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">Quantity</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">Quantity</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">int</span>&quot;<span class="cb1"> </span><span class="cb3">not-null</span><span class="cb1">=</span>&quot;<span class="cb1">true</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &nbsp; &lt;</span><span class="cb2">property</span><span class="cb1"> </span><span class="cb3">name</span><span class="cb1">=</span>&quot;<span class="cb1">DiscountPercentage</span>&quot;<span class="cb1"> </span><span class="cb3">column</span><span class="cb1">=</span>&quot;<span class="cb1">DiscountPercentage</span>&quot;<span class="cb1"> </span><span class="cb3">type</span><span class="cb1">=</span>&quot;<span class="cb1">double</span>&quot;<span class="cb1"> /&gt;</span></p>
<p class="cl"><span class="cb1">&nbsp; &lt;/</span><span class="cb2">class</span><span class="cb1">&gt;</span></p>
</div>
<p></code></p>
<p>It&#8217;s pretty easy&#8230; each property that shouldn&#8217;t be changed after creation is mapped with the nosetter.camelcase access strategy.  That means NHibernate uses the private field to set the value directly after creation,  but will use the getters whenever it needs to read the data from the entity.</p>
<p>As you can see, without too much trouble you can make sure that your entities always have their required data, and that properties that shouldn&#8217;t change after creation can&#8217;t be modified either.</p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/03/entities-required-properties-and-properties-that-shouldnt-be-modified/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>What Would You Like To See In My Upcoming NHibernate Examples?</title>
		<link>http://davybrion.com/blog/2009/03/what-would-you-like-to-see-in-my-upcoming-nhibernate-examples/</link>
		<comments>http://davybrion.com/blog/2009/03/what-would-you-like-to-see-in-my-upcoming-nhibernate-examples/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 15:35:53 +0000</pubDate>
		<dc:creator>Davy Brion</dc:creator>
				<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://davybrion.com/blog/?p=1170</guid>
		<description><![CDATA[The original version of my NHibernate Mapping Examples was pretty popular, but they were based on NHibernate 1.2 and only showed some of the basics.  I have plans to create a completely new version of these examples based on NHibernate 2.1.  I want the examples to be suitable for people who are entirely [...]]]></description>
			<content:encoded><![CDATA[<p>The original version of my <a href="http://davybrion.com/blog/2007/07/nhibernate-mapping-examples/">NHibernate Mapping Examples</a> was pretty popular, but they were based on NHibernate 1.2 and only showed some of the basics.  I have plans to create a completely new version of these examples based on NHibernate 2.1.  I want the examples to be suitable for people who are entirely new to NHibernate as an easy way to learn, as well as offering value to experienced NHibernate users by showing off some more advanced features.</p>
<p>It would be a downloadable Visual Studio solution, consisting of 2 projects.  One being the mapping files and the POCO&#8217;s, the other being a test (as in: consisting of automated tests) project which would contain the code of various usage scenarios to demonstrate various features of NHibernate.</p>
<p>I already have some ideas of stuff i definitely want in these examples, but i&#8217;d also like to hear from you what you would like to see in these examples.  So, if there is anything you&#8217;d like to see in there, let me know <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Obviously, i can&#8217;t promise that everything you ask for will be included but i&#8217;ll try anyway <img src='http://davybrion.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://davybrion.com/blog/2009/03/what-would-you-like-to-see-in-my-upcoming-nhibernate-examples/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
