<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Derik Whittaker : HowTo, NHibernate</title><link>http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/NHibernate/default.aspx</link><description>Tags: HowTo, NHibernate</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Hey, NHibernate give me back my milliseconds</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2010/02/22/hey-nhibernate-give-me-back-my-milliseconds.aspx</link><pubDate>Mon, 22 Feb 2010 22:47:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:55492</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=55492</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=55492</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2010/02/22/hey-nhibernate-give-me-back-my-milliseconds.aspx#comments</comments><description>&lt;p&gt;Have you ever noticed that out of the box NHibernate&amp;rsquo;s DateTime type will truncate/ignore your milliseconds for DateTime fields?&amp;nbsp; If you do not believe me check out this &lt;a href="https://www.hibernate.org/hib_docs/nhibernate/html/mapping.html#mapping-types-basictypes"&gt;post&lt;/a&gt;.&amp;nbsp; If you think about why it does this it will become clear, NHibernate runs against MANY databases and each one of them stores DateTime values slightly different.&amp;nbsp; However all of them store basic YYYY-MM-DD : HH:MM:SS.&lt;/p&gt;
&lt;p&gt;If you google how to resolve this issue you will find a few a &lt;a href="http://www.mostlyclean.com/post/2007/11/Increasing-DateTime-storage-precision-in-Nhibernate-%28and-Castle-ActiveRecord%29.aspx"&gt;post&lt;/a&gt; that suggests you create a custom User Type (IUserType).&amp;nbsp; Although I am sure this will work, this just seems like such overkill for the problem.&lt;/p&gt;
&lt;p&gt;What I was able to do was setup my mapping in FluentNHibernate as such&lt;/p&gt;
&lt;p&gt;Map( x =&amp;gt; x.MyField, &amp;quot;My_Field&amp;quot; ).CustomTypeIs(&amp;quot;timestamp&amp;quot;);&lt;/p&gt;
&lt;p&gt;By adding the .CustomTypeIs attribute (i tried CustomSqlTypeIs but this did not work) NHibernate was able to save my DateTime property into a DateTime (not Timestamp or DateTime2) field with the milliseconds inplace.&lt;/p&gt;
&lt;p&gt;Hope this helps,&lt;/p&gt;
&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=55492" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/FluentNhibernate/default.aspx">FluentNhibernate</category></item><item><title>NHiberante and Join types in your mappings Select vs Join</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2010/01/11/nhiberante-and-join-types-in-your-mappings-select-vs-join.aspx</link><pubDate>Mon, 11 Jan 2010 20:34:30 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:54971</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=54971</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=54971</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2010/01/11/nhiberante-and-join-types-in-your-mappings-select-vs-join.aspx#comments</comments><description>&lt;p&gt;When you are setting up your NHibernate mappings you must pay close attention to the way you setup your relationships between your entities.&amp;#160; Recently I started profiling some of our statements and was shocked to see how some of them had a metric-crap ton of joins when they only needed one or two.&amp;#160; After a bit of looking I realized that we had explicitly set FetchType to .Join (via Fluent NHibernate) and this was a big no-no.&amp;#160; &lt;/p&gt;  &lt;p&gt;When you setup your associations to be join associations each time you use a entity you will get (for free :) ) the associations for that entity.&amp;#160; However, as you may guess this can be very, very expensive and not the desired outcome.&amp;#160; Below is how changing my FetchType from .Join to .Select (also, .Select is the default if you do not specify any FetchType).&lt;/p&gt;  &lt;p&gt;This is the SQL output when everything was setup for .Join&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;FROM   RES_Basic this_
       inner join Res_Role roles1_
         on this_.RESOURCE_ID = roles1_.RESOURCE_ID
       left outer join O_BRANCH branch4_
         on roles1_.BRANCH_ID = branch4_.BRANCH_ID
       left outer join A_PROVIDER_TAXONOMY providerta5_
         on roles1_.TAXONOMY_ID = providerta5_.TAXONOMY_ID
       left outer join O_TEAM team6_
         on roles1_.TEAM_ID = team6_.TEAM_ID
       left outer join RES_Basic resource7_
         on roles1_.RESOURCE_ID = resource7_.RESOURCE_ID&lt;/pre&gt;

&lt;p&gt;This is the output after we changed to .Select (and setup my criteria to explicitly reference my Res_Role table)&lt;/p&gt;

&lt;pre class="c#" name="code"&gt;FROM   RES_Basic this_
       inner join Res_Role roles1_
         on this_.RESOURCE_ID = roles1_.RESOURCE_ID&lt;/pre&gt;

&lt;p&gt;As you can see, when I do it right I am only joining to the tables I want and this can lead to a huge performance savings.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=54971" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>NHibernate and “The multi-part identifier … could not be bound” Exception</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2010/01/05/nhibernate-and-the-multi-part-identifier-could-not-be-bound-exception.aspx</link><pubDate>Tue, 05 Jan 2010 12:48:42 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:54916</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=54916</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=54916</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2010/01/05/nhibernate-and-the-multi-part-identifier-could-not-be-bound-exception.aspx#comments</comments><description>&lt;p&gt;Today as I was creating a new NHibernate Criteria statement everything was working fine UNTIL I added the where clause.&amp;#160; At this point I started to get the following exception (which was seen via &lt;a href="http://nhprof.com/"&gt;NHibernate Profier&lt;/a&gt;).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;WARN:      &lt;br /&gt;System.Data.SqlClient.SqlException: The multi-part identifier &amp;quot;doc2_.NAME&amp;quot; could not be bound.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;My criteria statement looked something like this&lt;/p&gt;  &lt;pre class="c#" name="code"&gt;var query = Session.CreateCriteria( typeof(DocumentSection), &amp;quot;docSection&amp;quot; )
    .CreateAlias( &amp;quot;docSection.DocumentSegment&amp;quot;, &amp;quot;docSegment&amp;quot;, JoinType.None )
    .CreateAlias( &amp;quot;docSegment.DocumentDefinition&amp;quot;, &amp;quot;doc&amp;quot;, JoinType.InnerJoin )
    .... MORE STUFF HERE

    .Add( Restrictions.Eq( &amp;quot;doc.Name&amp;quot;, documentName ) )

    .SetResultTransformer( new DistinctRootEntityResultTransformer() )
    .List();&lt;/pre&gt;

&lt;p&gt;When I first saw this error it did not make any sense as I KNEW that there was in fact a Name field on the object I was trying to hydrate.&amp;#160; But if you look closely at the first .CreateAlias you will notice the issue.&amp;#160; For my JoinType I had set it to &lt;font color="#ff0000"&gt;JoinType.None &lt;/font&gt;&lt;font color="#000000"&gt;and not &lt;font color="#ff0000"&gt;JoinType.Inner &lt;/font&gt; so when NHibernate wanted to hydrate my object it could not because as far as it was concerned the object was not meant to be hydrated.&lt;/font&gt;&lt;/p&gt;

&lt;p&gt;To resolve this issue I changed the JoinType to be Inner and all worked.&amp;#160; Below is the working code. &lt;/p&gt;

&lt;pre class="c#" name="code"&gt;var query = Session.CreateCriteria( typeof(DocumentSection), &amp;quot;docSection&amp;quot; )
    .CreateAlias( &amp;quot;docSection.DocumentSegment&amp;quot;, &amp;quot;docSegment&amp;quot;, JoinType.InnerJoin )
    .CreateAlias( &amp;quot;docSegment.DocumentDefinition&amp;quot;, &amp;quot;doc&amp;quot;, JoinType.InnerJoin )
    .... MORE STUFF HERE

    .Add( Restrictions.Eq( &amp;quot;doc.Name&amp;quot;, documentName ) )

    .SetResultTransformer( new DistinctRootEntityResultTransformer() )
    .List();&lt;/pre&gt;

&lt;p&gt;Till next time&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=54916" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>NHProf and performance issues while running under VM</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/08/04/nhprof-and-performance-issues-while-running-under-vm.aspx</link><pubDate>Tue, 04 Aug 2009 20:55:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:49838</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=49838</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=49838</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/08/04/nhprof-and-performance-issues-while-running-under-vm.aspx#comments</comments><description>&lt;p&gt;Recently I was forced to do full time development on my MacBook because I killed my Windows Laptop (btw, turns out it is a bad idea to spill milk on the keyboard of a laptop&amp;hellip; who knew).&amp;nbsp; When doing this I was running Windows7 under VM via Fusion.&amp;nbsp; Everything was working great&amp;hellip;&amp;hellip;until I fired up &lt;a href="http://www.nhprof.com/"&gt;NHProf&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The second I fired up NHProf my VM basically stopped working.&amp;nbsp; To say the least Ii was a bit perplexed.&amp;nbsp; To confirm it was NHProf and not something else, I killed the app to see if everything would go back to normal.. sure enough it did.&lt;/p&gt;
&lt;p&gt;At this point I was pretty sure NHProf was the culprit.&amp;nbsp; In order to figure out the issue or if this was an isolated issue I asked the &lt;a href="http://www.twitter.com"&gt;twitterverse&lt;/a&gt; and of course my good buddy &lt;a href="http://devlicio.us/blogs/rob_eisenberg/"&gt;Rob Eisenberg&lt;/a&gt; (who happens to be one of the authors of the GUI) asked me to try something.&lt;/p&gt;
&lt;p&gt;He asked me to turn off hardware acceleration on the gfx card and try it again.&amp;nbsp; I did as he asked and&amp;hellip;. bam, the problem went away.&amp;nbsp; Rob is not 100% sure what the cause is, but he is currently having a conversation with the WPF team to see if there is a known issue with this and will report back his findings and I will do so as well.&lt;/p&gt;
&lt;p&gt;So, long story short.&amp;nbsp; If running under VM and NHProf is dogging make sure you have hardware acceleration turn off and that should resolve your issue.&lt;/p&gt;
&lt;p&gt;Till next time. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=49838" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Joining NHibernate Transaction with ADO SqlTransaction</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/06/15/joining-nhibernate-transaction-with-ado-sqltransaction.aspx</link><pubDate>Mon, 15 Jun 2009 16:35:54 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:47935</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=47935</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=47935</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/06/15/joining-nhibernate-transaction-with-ado-sqltransaction.aspx#comments</comments><description>&lt;p&gt;Recently (ok, today) I needed to drop down into ADO to call a procedure in our code.&amp;#160; I was not too happy with it, but either my lack of knowledge or lack of will to figure it out mandated it.&amp;#160; What I needed to do was create a build-insert process and using NHibernate was not the right solution for performance reasons.&lt;/p&gt;  &lt;p&gt;When I first created my code, seen below my tests worked fine.&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;public void AssignNewDestinationToPatients( Destination destination )
{
    var connection = (SqlConnection) Session.Connection;
    
    var sqlCommand = new SqlCommand
                         {
                             CommandType = CommandType.StoredProcedure,
                             CommandText = StoredProcedures.DO_SOMETHING,
                             Connection = connection,                                     
                         };

    sqlCommand.Parameters.Add( new SqlParameter( &amp;quot;DestinationID&amp;quot;, destination.DestinationID ) );

    sqlCommand.ExecuteNonQuery()    ;
}&lt;/pre&gt;

&lt;p&gt;However, once this call was wrapped around an NH transaction i would receive the following error:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;{&amp;quot;ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.&amp;#160; The Transaction property of the command has not been initialized.&amp;quot;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Of course the first I tried to do was cast the NH transaction to a sql transaction and provide that to the command object.&amp;#160; However, that is NOT possible.&amp;#160; The great news for me was the NH has the capacity to enlist a sql commmand and add it to its transaction.&amp;#160; The code below shows how to do this.&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public void AssignNewDestinationToPatients( Destination destination )
{
    var connection = (SqlConnection) Session.Connection;
    
    var sqlCommand = new SqlCommand
                         {
                             CommandType = CommandType.StoredProcedure,
                             CommandText = StoredProcedures.DO_SOMETHING,
                             Connection = connection,                                     
                         };

    // this is the magic code
    if ( Session.Transaction != null &amp;amp;&amp;amp; Session.Transaction.IsActive )
    {
        Session.Transaction.Enlist( sqlCommand );
    }

    sqlCommand.Parameters.Add( new SqlParameter( &amp;quot;DestinationID&amp;quot;, destination.DestinationID ) );

    sqlCommand.ExecuteNonQuery()    ;
}&lt;/pre&gt;

&lt;p&gt;So, if you need to drop down to ADO from NHibernate and you need to use transactions, this solution should work out well for you.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;

&lt;p&gt;P.S. If there is a better, simpler way please let me know.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=47935" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>NHibernate &amp; SetProjections/SetProjections w/ List Gotcha</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/05/27/nhibernate-amp-setprojects-setprojects-w-list-gotcha.aspx</link><pubDate>Wed, 27 May 2009 15:21:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:47219</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=47219</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=47219</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/05/27/nhibernate-amp-setprojects-setprojects-w-list-gotcha.aspx#comments</comments><description>&lt;p&gt;Today I was needing to create a query which looked a bit like this:&lt;/p&gt;
&lt;p&gt;SELECT&amp;nbsp;&amp;nbsp; max(this_.SEQUENCE) as y0_, 
  &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; this_.ADMISSION_ID&amp;nbsp; as y1_ 
  &lt;br /&gt;FROM&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; PT_Status this_ 
  &lt;br /&gt;GROUP BY this_.ADMISSION_ID&lt;/p&gt;
&lt;p&gt;As you can see, I was trying to do a group by one column and a Max() on another column (legacy DB&amp;rsquo;s gotta love them).&lt;/p&gt;
&lt;p&gt;Since I only wanted to project a few properties I decided to use project and provide a list of columns I wanted, my code looked like:&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;var detachedCriteria = CriteriaBuilder.CreateCritieraFor()
	.SetProjection( 
		Projections.ProjectionList()                    
        		.Add( Projections.Property( &amp;quot;Sequence&amp;quot; ) ) 
	                .Add( Projections.Property( &amp;quot;AdmissionID&amp;quot; ) )                    
			)                
	.SetProjection( Projections.Max( &amp;quot;Sequence&amp;quot; ) )
	.SetProjection( Projections.GroupProperty( &amp;quot;AdmissionID&amp;quot; ) )
        .SetResultTransformer( Transformers.AliasToBean( typeof( Status ) ) );&lt;/pre&gt;
&lt;p&gt;When I would run this code it would not give me the sql I wanted, and everything looked ok.&amp;nbsp;&amp;nbsp; Then through trial and error I realized my issue.&amp;nbsp; The code below is the code which works&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;var detachedCriteria = CriteriaBuilder.CreateCritieraFor()
	.SetProjection( 
		Projections.ProjectionList()                    
        		.Add( Projections.Max( &amp;quot;Sequence&amp;quot; ) ) 
	                .Add( Projections.GroupProperty( &amp;quot;AdmissionID&amp;quot; ) )                    
			)                
        .SetResultTransformer( Transformers.AliasToBean( typeof( Status ) ) );&lt;/pre&gt;
&lt;p&gt;If you look at the first example i am both setting up my column projections and my group/max projects, but they are on the same column (not needed) and my group/max projections is OUTSIDE my first projection list.&amp;nbsp; Turns out that I only needed my first projection list as it would setup the group/max as well as my return columns.&lt;/p&gt;
&lt;p&gt;Hope this helps.&lt;/p&gt;
&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=47219" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Pay attention to the difference between Expression.Lt &amp; Expression.LtProperty</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/05/06/pay-attention-to-the-difference-between-expression-lt-amp-expression-ltproperty.aspx</link><pubDate>Thu, 07 May 2009 01:33:20 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46538</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=46538</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=46538</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/05/06/pay-attention-to-the-difference-between-expression-lt-amp-expression-ltproperty.aspx#comments</comments><description>&lt;p&gt;Pop quiz, what is the difference between Expression.Lt (.Gt, .Eq, etc) and Expression.LtProperty (.GtProperty, .EqProperty, etc)? If you know the answer off the top of your head you win the prize… What is the prize you may ask? NOTHING….&lt;/p&gt;  &lt;p&gt;Anyway, I needed to create a criteria query where I wanted to filter out the data where the date in one table was &lt;font color="#80ffff"&gt;&lt;font color="#0000ff"&gt;Less Than&lt;/font&gt; &lt;/font&gt;&lt;font color="#000000"&gt;the date in another table.&amp;#160; I thought this was pretty straight forward.&amp;#160; I created an expression part like below&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&lt;font color="#0080ff"&gt;criteria.Add( Expression.Lt( “DateFieldOne”, “DateFieldTwo ) );&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;However, when I ran my test to see if my criteria was correct I received the following error:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;NHibernate.QueryException: Type mismatch in NHibernate.Criterion.SimpleExpress: DateFieldOne expected type System.DateTime, actual System.String&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I have to say that I as stumped, everything looked right and I even took a look at the restriction information which was generated.&amp;#160; You can see it below.&lt;/p&gt;  &lt;p&gt;{(DateFieldONe &amp;lt; DateFieldTwo)}&lt;/p&gt;  &lt;p&gt;To the untrained eye (that would be mine) it looked right.&amp;#160; After a few minutes of staring at this (and scratching my ass for a bit :) ) it dawned on me.&amp;#160; NHibernate was not comparing my fields, it was trying to compare the column on the left (DateFieldOne) to the ‘string’ value of DateFieldTwo.&amp;#160; At this point I knew what I needed to do… Use the .LtProperty.&amp;#160; When I changed from .Lt to .LtProperty everything worked out just right.&lt;/p&gt;  &lt;p&gt;My new criteria logic looks like:&lt;/p&gt;  &lt;p&gt;&lt;font color="#0080ff"&gt;criteria.Add( Expression.LtProperty( “DateFieldOne”, “DateFieldTwo ) );&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;So the moral of the story is this.&amp;#160; When you are trying to create a criteria selection and you are trying to compare 2 columns, not a column against a value make sure you use the *Property command on the Expression object (.LtProperty, .GtProperty, .EqProperty, etc).&lt;/p&gt;  &lt;p&gt;Hope this helps,&lt;/p&gt;  &lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46538" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Debugging NHibernate Exceptions</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/05/05/debugging-nhibernate-exceptions.aspx</link><pubDate>Tue, 05 May 2009 09:14:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46503</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=46503</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=46503</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/05/05/debugging-nhibernate-exceptions.aspx#comments</comments><description>&lt;p&gt;When developing your data access layer with NHibernate you are bound to run into some pretty nasty exceptions.&amp;nbsp; Many times the exceptions may be nasty, but at least they explain the problem in enough detail to allow you to solve the problem.&amp;nbsp; But what do we do when the exceptions do not convey enough information to allow us to simply and easily spot our issue?&amp;nbsp; Simply, time to bust out the shovel and pick ax and start digging for the nugget of information which will allow you to find your solution.&lt;/p&gt;
&lt;p&gt;The good news is there is at least 2 (could be many more) ways you can get detailed information on what NHibernate is doing and what possible be wrong.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Utilize &lt;/b&gt;&lt;a href="http://www.nhprof.com/"&gt;&lt;b&gt;NHibernate Profiler&lt;/b&gt;&lt;/a&gt;    &lt;br /&gt;If you are using NHibernate and you are NOT using NHProfiler then you are basically writing code with one hand tied behind your back.&amp;nbsp; This tool can and will help you solve so many problems you will be amazed.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;But when hunting bugs NHProf is practically useful because it gives you a very clean way to see the exact sql which is being generated and executed in real time (or damn close to it).&amp;nbsp; Implementing NHprof could not be easier and takes a mere 3 steps and 1 line of code.&lt;/p&gt;
&lt;p&gt;To Implement all you do is&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Add reference to HibernatingRhinos.NHibernate.Profiler.Appender.dll class in your project.&lt;/li&gt;
&lt;li&gt;Add this one line of code at the entry point of your application (or unit test)     &lt;br /&gt;HibernatingRhinos.NHibernate.Profiler.Appender.NHibernateProfiler.Initialize();&lt;/li&gt;
&lt;li&gt;Launch the GUI HibernatingRhinos.NHibernate.Profiler.Client.exe&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;b&gt;Utilize the logging which is build into NHibernate via Log4Net&amp;nbsp; &lt;br /&gt;&lt;/b&gt;Now sometimes even NHProfiler is not going to solve your problems and when this is the case you are in for some fun.&amp;nbsp; I have found the best way to debug what is going on is to turn on logging for Nhibernate.&amp;nbsp; Now I am not going to go into depth on how to do this as post on &lt;a href="http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/07/01/how-to-configure-log4net-for-use-with-nhibernate.aspx"&gt;Hibernateing Rhinos&lt;/a&gt; and &lt;a href="https://www.hibernate.org/364.html"&gt;Nhiberate.org&lt;/a&gt; do a great job of providing this information.&lt;/p&gt;
&lt;p&gt;Once you have your app.config or your web.config setup all you need to do is add this line of code at the entry point of your application (or unit tests)   &lt;br /&gt;log4net.Config.XmlConfigurator.Configure()&lt;/p&gt;
&lt;p&gt;When implementing logging with Log4Net I would suggest 2 things&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Turn on DEBUG logging, this will produce a ton of content but is needed&lt;/li&gt;
&lt;li&gt;If using a file appender up the max file size to be at least 1mb. Anything lower will simply produce too many files and you will be swimming in a see of log files&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you utilize the above 2 techniques for trouble shooting/debugging your nhibernate issues you should be able to resolve most of them in no time flat.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Till next time,   &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46503" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Creating a nested ‘Or’ statement with NHibernate using the Criteria convention</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/04/21/creating-a-nested-or-statement-with-nhibernate-using-the-criteria-convention.aspx</link><pubDate>Tue, 21 Apr 2009 21:26:33 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46138</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=46138</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=46138</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/04/21/creating-a-nested-or-statement-with-nhibernate-using-the-criteria-convention.aspx#comments</comments><description>&lt;p&gt;As I pointed in a prior post (&lt;a href="http://devlicio.us/blogs/derik_whittaker/archive/2009/04/16/creating-a-select-count-with-nhibernate-using-criteria.aspx"&gt;here&lt;/a&gt;) when trying to learn to harness the power of NHibernate sometimes the ‘simple’ can be a bit daunting at first.&amp;#160; For instance how do you create a query with NHibernate that looks a little like the information below?&lt;/p&gt;  &lt;pre class="csharp" name="code"&gt;Where ....
	AND 
	( 
		( a = x AND b = true )
		or
		( a = y AND b = true )
		or 
		( a = z AND b = true )
	)&lt;/pre&gt;

&lt;p&gt;This would&amp;#160; be actually pretty easy if all you needed to do was have a single Or statement because there is a helper method in NHibernate (&lt;font color="#0080ff"&gt;Expresssion&lt;/font&gt;.Or) which takes in 2 parts.&amp;#160; However, what do you do if you need to both have more than 2 parts to your Or statement as well as add in a And clause to each one.&amp;#160; Well, you have to break away from the helper methods and go straight to the &lt;font color="#0080ff"&gt;Restrictions&lt;/font&gt; class.&lt;/p&gt;

&lt;p&gt;The code below is a snippet which should help to show how you can build a criteria which creates the final sql in the same way as above.&lt;/p&gt;

&lt;pre class="csharp" name="code"&gt;// criteria is an instance of the DetachedCriteria object

var queuedCriterion = new List&amp;lt;AbstractionCriterion&amp;gt;();

// build out each of the &amp;#39;Or&amp;#39; statements
foreach( var someObject in listOfSomeObjects )
{
	var partOneExpression = Expression.Eq( &amp;quot;A&amp;quot;, &amp;quot;x&amp;quot; );
	var partTwoExpression = Expression.Eq( &amp;quot;B&amp;quot;, true );
	queuedCriterion.Add( Expression.And( partOneExpression, partTwoExpression ) );
}

// put each of the &amp;#39;Or&amp;#39; statements into one disjunction.
// this will allow them to be nested on the same level
var orDisjunction = Restrictions.Disjunction();
foreach ( var criterion = queuedCriterion )
{
	orDisjunction.Add( criterion );
}

// finally add the full list &amp;#39;Or&amp;#39; into the main criteria object
criteria.Add( orDisjunction )&lt;/pre&gt;

&lt;p&gt;As you can see above&amp;#160; there is a bit of code needed to create this sql syntax when using the criteria, but it is not too bad (IMO).&amp;#160; The more I learn about NHibernate, the more I really start to appreciate its power and flexibility.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46138" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Creating a Select Count(*) with NHibernate using Criteria</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/04/16/creating-a-select-count-with-nhibernate-using-criteria.aspx</link><pubDate>Thu, 16 Apr 2009 12:18:19 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46075</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=46075</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=46075</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/04/16/creating-a-select-count-with-nhibernate-using-criteria.aspx#comments</comments><description>&lt;p&gt;As you are learning how to use NHibernate many of the ‘common’ things you are used to doing with standard SQL crop up.&amp;#160; One of them for me was to have the ability to perform a Count() query.&amp;#160; If I were using straight SQL my query may look something like this:&lt;/p&gt;  &lt;pre class="csharp" name="code"&gt;SELECT COUNT( FieldNameHere )
FROM SomeTableTable 
WHERE Field1Here = 51 
	AND Field2Here = 1 
	AND Field3Here = 1&lt;/pre&gt;

&lt;p&gt;Like many things in Nhibernate there are many ways to solve the same problem, but one way I found was to create the criteria query as below:&lt;/p&gt;

&lt;pre class="csharp" name="code"&gt;var count = (Int32) Session.CreateCriteria( typeof( SomeTableHere ) ) 
        .Add( Expression.Eq( &amp;quot;Field1Here&amp;quot;, 1) ) 
        .Add( Expression.Eq( &amp;quot;Field2Here&amp;quot;, (Int32) 2) ) 
        .Add( Expression.Eq( &amp;quot;Field3Here&amp;quot;, 3) ) 
	.SetProjection( Projections.Count( &amp;quot;CountFieldHere&amp;quot; ) ).UniqueResult();&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;And the result from the above syntax would produce the following (the sql below was given to me via &lt;a href="http://nhprof.com/"&gt;NHProfiler&lt;/a&gt; – kick ass tool EVERYONE should be using).&lt;/p&gt;

&lt;pre class="csharp" name="code"&gt;SELECT count(this_.OUTBOUND_STAGING_QUEUE_ID) as y0_ 
FROM   SomeTableHere this_ 
WHERE  this_.Field1Here= 51 /* @p0 */ 
       and this_.Field2Here = 1 /* @p1 */ 
       and this_.Field3Here = 1 /* @p2 */&lt;/pre&gt;

&lt;p&gt;As you can see creating a count query with NHibernate is pretty straight forward and will generate the exact SQL you would expect.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46075" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Simple example of using a Subquery in NHibernate when using ICriteria</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/04/06/simple-example-of-using-a-subquery-in-nhibernate-when-using-icriteria.aspx</link><pubDate>Mon, 06 Apr 2009 21:41:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:45402</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=45402</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=45402</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/04/06/simple-example-of-using-a-subquery-in-nhibernate-when-using-icriteria.aspx#comments</comments><description>&lt;p&gt;Of the many things that NHibernate is, simple and &amp;lsquo;straight forward&amp;rsquo; it is not (at times).&amp;nbsp; Recently I needed to do a SubQuery, so of course the first thing I did was try to Google it.&amp;nbsp; I was able to find quite a few examples on how to create and execute a subquery, but none of them had &lt;b&gt;ALL&lt;/b&gt; the information I was looking for.&lt;/p&gt;
&lt;p&gt;What was I looking for, well the &amp;lsquo;dummy&amp;rsquo; overview on what I should do.&amp;nbsp; To be exact I wanted the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Database layout (most had this, not all) &lt;/li&gt;
&lt;li&gt;Raw sql as if you were doing it by hand (a few had this) &lt;/li&gt;
&lt;li&gt;Clean/Simple example of how to create the SubQuery (some had this)      
&lt;ul&gt;
&lt;li&gt;Details on what the query was actually doing (not sure I saw this) &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The generated output of the sql which was created by NHibernate (some had this) &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Before we get started with creating and looking at the code, maybe it would be best if I gave an overview of the what I was trying to do which required a subquery.&amp;nbsp; I needed to return all header records (from Message_Queue table) who had a child record (from Message_Queue_Status table )which was in a given state.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;&lt;b&gt;Database Diagram:      &lt;br /&gt;&lt;/b&gt;Below you will find a simple database diagram of the 2 tables I was trying to query against.&amp;nbsp; The parent table in this diagram is the Message_Queue table.&amp;nbsp; This table hold the main information for a message which is going to be sent in our system.&amp;nbsp; The child table is the Message_Queue_Status table, this holds a record for the message for each step in the process.&amp;nbsp; With this table we can know at any point in time what status the sending message is in.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_0CE6698F.png"&gt;&lt;img title="image" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_44B8ADB2.png" border="0" height="286" width="354" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;&lt;b&gt;Raw SQL of what I needed NHibernate to generate:      &lt;br /&gt;&lt;/b&gt;What I did prior to trying to setup NHibernate was to manually create the sql for what I needed.&amp;nbsp; I do this many times because I can whip out the sql pretty quickly and easily and it provides me a better picture of what I need NHibernate to do.&amp;nbsp; The raw sql I created is below.&amp;nbsp; (Where you see the values 2 &amp;amp; 4, those would be enums when translated to NHibernate)&lt;/p&gt;
&lt;pre class="sql" name="code"&gt;SELECT MQ.*&lt;br /&gt;FROM [MESSAGE_QUEUE] MQ&lt;br /&gt;WHERE MQ.[DIRECTION_TYPE_ID] = 2&lt;br /&gt;	AND MQ.[MESSAGE_QUEUE_ID] IN ( &lt;br /&gt;		SELECT MESSAGE_QUEUE_ID FROM [MESSAGE_QUEUE_STATUS] WHERE [STATUS_TYPE_ID] &amp;lt;= 4&lt;br /&gt;	 )&lt;/pre&gt;
&lt;p&gt;&lt;b&gt;NHibernate code needed to create the query: 
    &lt;br /&gt;&lt;/b&gt;Once I knew what I needed to do, it was only a matter of translating that need over to NHibernate.&amp;nbsp; The thing that stumped me at first was how exactly to create the subquery.&amp;nbsp; The code below is the final working example needed to build the equivalent of the sql above.&lt;/p&gt;
&lt;pre class="c-sharp" name="code"&gt;var subCriteria = DetachedCriteria.For();&lt;br /&gt;subCriteria.SetProjection( Projections.Property( &amp;quot;MessageQueue.MessageQueueID&amp;quot; ) )&lt;br /&gt;	.Add( Expression.Le( &amp;quot;StatusTypeID&amp;quot;, 4 ) );&lt;br /&gt;&lt;br /&gt;var criteria = session.CreateCriteria( typeof( MessageQueue ) )&lt;br /&gt;	.Add( Expression.Eq( &amp;quot;DirectionTypeID&amp;quot;, (Int32) MessageDirectionType.Outbound ) )&lt;br /&gt;        .Add( Subqueries.PropertyIn( &amp;quot;MessageQueueID&amp;quot;, subCriteria ) );&lt;/pre&gt;
&lt;p&gt;Taking a look at the NHibernate code above, you really need to break down into two parts.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The subquery 
    &lt;br /&gt;The top part is the logic/code needed in order to build: 
    &lt;br /&gt;&lt;i&gt;SELECT MESSAGE_QUEUE_ID FROM [MESSAGE_QUEUE_STATUS] WHERE [STATUS_TYPE_ID] &amp;lt;= 4 
      &lt;br /&gt;&lt;/i&gt;
    &lt;br /&gt;Once you have this part built you will need to apply it to the main part of the query 
    &lt;/li&gt;
&lt;li&gt;The main query 
    &lt;br /&gt;The main query is where all the magic happens.&amp;nbsp; This is where you need to apply your sub-select and where the data will be filtered.
    &lt;br /&gt;
    &lt;br /&gt;You will notice that I am using the &amp;lsquo;Subqueries.PropertyIn&amp;rsquo; syntax.&amp;nbsp; This will generate the the following SQL
    &lt;br /&gt;MQ.[MESSAGE_QUEUE_ID] IN ( &amp;hellip;.. ) which is what you are looking for.
    &lt;br /&gt;You should also take note that I am using &amp;ldquo;MessageQueueID&amp;rdquo; as my property, but when it gets rendered it is the correct column name in the db as defined by the mappings.&amp;nbsp; I point this out as many first time NHibernate users (myself being one of them) will try to use the db column name, not the property name.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Now if you have done everything correctly you should be able to run your sub query and it will produce the data you are looking for.&lt;/p&gt;
&lt;p&gt;I will also point out that if you are NOT using &lt;a href="http://nhprof.com/"&gt;NHProfiler&lt;/a&gt; for your NHibernate development, you are simply wasting debug cycles.&lt;/p&gt;
&lt;p&gt;Hope this helps someone.&lt;/p&gt;
&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=45402" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>NHibernate and ‘Invalid Index N for this SqlParameterCollection with Count=N error’</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/03/19/nhibernate-and-invalid-index-n-for-this-sqlparametercollection-with-count-n-error.aspx</link><pubDate>Thu, 19 Mar 2009 16:00:08 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:45054</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=45054</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=45054</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/03/19/nhibernate-and-invalid-index-n-for-this-sqlparametercollection-with-count-n-error.aspx#comments</comments><description>&lt;p&gt;If you have ever used NHibernate I am sure you have encounted the error ‘Invalid Index ‘N’ for this SqlParameterCollection with Count=N’ (where N is any number) exception when trying to create your mappings.&lt;/p&gt;  &lt;p&gt;If you are completely new to NHibernate, as I am I am sure this one has you scratching your head saying…. WTF.&lt;/p&gt;  &lt;p&gt;The good news is that ‘normally’ the solution to this problem is pretty easy, but before I tell you the answer let me explain the issue.&lt;/p&gt;  &lt;p&gt;Take a look at the code below&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;public EpisodeMap()
{
	WithTable( &amp;quot;Episode&amp;quot; );

	Id( x =&amp;gt; x.ID ).GeneratedBy.Identity();

        Map( x =&amp;gt; x.LevelTypeID );
        Map( x =&amp;gt; x.Name );
        Map( x =&amp;gt; x.Description );
        Map( x =&amp;gt; x.EpisodeNumber );
        Map( x =&amp;gt; x.EpisodeDate );
        Map( x =&amp;gt; x.CreatedDate );
	Map( x =&amp;gt; x.Enabled );

	References( x =&amp;gt; x.EpisodeLevel )
        .WithForeignKey( &amp;quot;LevelTypeID&amp;quot; ).TheColumnNameIs( &amp;quot;LevelTypeID&amp;quot; )
        .Access.AsCamelCaseField( Prefix.Underscore )
	.FetchType.Join();

}&lt;/pre&gt;

&lt;p&gt;Take notice to the mapping above.&amp;#160; I have a many-to-one mapping for EpisodeLevel, but I have also created and mapped the FK to EpisodeLevel as LevelTypeID.&lt;/p&gt;

&lt;p&gt;The issue (as i have experienced it) is this:&lt;/p&gt;

&lt;p&gt;Because I have mapped my FK to the Episode Level table as .LevelTypeID as well as to the EpisodeLevel entity NH is going to try to create multiple associations on that field.&amp;#160; However it cannot because that is not correct.&lt;/p&gt;

&lt;p&gt;To solve this issue (mostly in my experience) all you need to do is remove the following line 
  &lt;br /&gt;Map( x =&amp;gt; x.LevelTypeID ); &lt;/p&gt;

&lt;p&gt;If you MUST populate the LevelTypeID property at the top level, do so by providing the value as a pass through from Episode Level as such: 
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public Int32 LevelTypeID
{
	get { return EpisodeLevel.LevelTypeID; }
}&lt;/pre&gt;

&lt;p&gt;I hope this helps someone.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=45054" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/FluentNhibernate/default.aspx">FluentNhibernate</category></item><item><title>Verifying that that your data is Eagerly loaded in NHibernate</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/03/06/verifying-that-that-your-data-is-eagerly-loaded-in-nhibernate.aspx</link><pubDate>Fri, 06 Mar 2009 13:27:11 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44845</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=44845</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=44845</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/03/06/verifying-that-that-your-data-is-eagerly-loaded-in-nhibernate.aspx#comments</comments><description>&lt;p&gt;In my last &lt;a href="http://devlicio.us/blogs/derik_whittaker/archive/2009/03/05/eager-loading-a-one-to-many-collection-w-nhibernate.aspx"&gt;post&lt;/a&gt; I talked about how I needed to eager load my data in order to send it back across the wire.&amp;#160; Normally I am not a big fan of creating tests to ensure that I can hit the database, but in this case the act of eager loading needs to be verified and constant.&amp;#160; &lt;/p&gt;  &lt;p&gt;When I set out to create my tests, I was not exactly sure how I could verify this.&amp;#160; The good news is there is a utility class called &lt;a href="http://www.surcombe.com/nhibernate-1.2/api/html/T_NHibernate_NHibernateUtil.htm"&gt;NHibernateUtil&lt;/a&gt; which has a method on it called .IsInitialized() which will return a bool.&amp;#160; Below is the unit test I put together to ensure my data was always being eagerly loaded.&amp;#160; Yes I know that this test does NOT take into account any new data which may need to be eagerly loaded, but it is at least a step in the right direction.&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;[Test]
public void FetchDestinations_EnsureDataIsEagerLoaded()
{
    var repository = new DestinationRepository();

    IList destinations = repository.FetchDestinations();

    // want to ensure that the data was eager loaded as we need/want
    var destination = destinations.FirstOrDefault();

    // incase there is no data in the DB
    if ( destination != null )
    {
        Assert.That( NHibernateUtil.IsInitialized( destination.Endpoint ), Is.True );
        Assert.That( NHibernateUtil.IsInitialized( destination.AssignedMessageTypeses ), Is.True );                
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see from my test, I do need to add in come logic to ensure I am hitting my database and gathering data.&amp;#160; I am normally not a fan of this, but I think it is needed here as I do not want to fail my test if there is no data. When this test runs I will always know that my data is being eagerly loaded which fulfills my needs.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44845" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Eager loading a One-to-Many collection w/ NHibernate</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/03/05/eager-loading-a-one-to-many-collection-w-nhibernate.aspx</link><pubDate>Thu, 05 Mar 2009 21:14:44 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44833</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=44833</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=44833</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/03/05/eager-loading-a-one-to-many-collection-w-nhibernate.aspx#comments</comments><description>&lt;p&gt;At work I have a section of code which I need to eager load all my data in order to pass that data back across the wire.&amp;#160; I thought I had it all setup correctly, but then I realized that I was not returning back unique results from my query.&lt;/p&gt;  &lt;p&gt;Imagine I have the following Schema&lt;/p&gt;  &lt;p&gt;&lt;a href="http://devlicio.us/blogs/derik_whittaker/image_74E52EA7.png"&gt;&lt;img title="image" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="484" alt="image" src="http://devlicio.us/blogs/derik_whittaker/image_thumb_579788F0.png" width="456" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;My current need was to get all Destinations in the database (we know it is a small number and this is for the edit screen) and have it eager load the endpoint (which you actually get for free) and the Assigned_Message_Types&lt;/p&gt;  &lt;p&gt;Originally setup my Criteria selection as below&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;var result = Session.CreateCriteria( typeof( Destination ) )                                
	.SetFetchMode( &amp;quot;Endpoint&amp;quot;, FetchMode.Eager )
        .SetFetchMode( &amp;quot;AssignedMessageTypeses&amp;quot;, FetchMode.Eager )        
        .List();&lt;/pre&gt;

&lt;p&gt;When I ran the query above, I expected to get 2 records back, one for each destination in the database.&amp;#160; However, I received 4 of them back.&amp;#160; The first 3 were the same, and the 4th one was different.&amp;#160; As you could imagine this is NOT what I expected.&amp;#160; I thought I would reach out to &lt;a href="http://codebetter.com/blogs/kyle.baley/default.aspx"&gt;Kyle Baley&lt;/a&gt; (&lt;a href="http://www.twitter.com/kbaley"&gt;@kbaley&lt;/a&gt;) for some help on this, but turns out he was having the same issue recently.&amp;#160; Good thing for both of us the Twitterverse was able to lend a helpful hand.&amp;#160; James Kovacs (&lt;a href="http://twitter.com/jameskovacs"&gt;@jamesKovacs&lt;/a&gt;) along with someone else (sorry, forgot our handle) pointed both of us to the following 2 posts.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/06/eager-loading-aggregate-with-many-child-collections.aspx"&gt;Eager Loading aggregate with many child collections&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://nhforge.org/wikis/howtonh/get-unique-results-from-joined-queries.aspx"&gt;Get unique results from joined queries&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I decided to get the usage of DistinctRootEntityResultTransformer a try, and the code below is what worked for me.&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;var result = Session.CreateCriteria( typeof( Destination ) )                                
	.SetFetchMode( &amp;quot;Endpoint&amp;quot;, FetchMode.Eager )
        .SetFetchMode( &amp;quot;AssignedMessageTypeses&amp;quot;, FetchMode.Eager )        
	
	// this is the magic line    
        .SetResultTransformer( new DistinctRootEntityResultTransformer() )
        .List();&lt;/pre&gt;

&lt;p&gt;By adding the DistinctRootEntityResultTransformer transformer to my query I now get 2 rows of data, which is exactly what I needed/wanted.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44833" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category></item><item><title>Invalid Column name exception with FluentNhibernate and References (many-to-one)</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2009/02/13/invalid-column-name-exception-with-fluentnhibernate-and-references-many-to-one.aspx</link><pubDate>Fri, 13 Feb 2009 08:51:36 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44171</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=44171</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=44171</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2009/02/13/invalid-column-name-exception-with-fluentnhibernate-and-references-many-to-one.aspx#comments</comments><description>&lt;p&gt;One exception you may run across while using Fluent Nhibernate (or straight up NHibernate) is System.Data.SqlClient.SqlException: Invalid column name ‘……’.&amp;#160; This is normally caused because you did not provide the correct column name when doing your mapping.&lt;/p&gt;  &lt;p&gt;Lets take a look at the code below which is trying to map a many-to-one relationship to another entity.&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;References( x =&amp;gt; x.BusinessUnit )
        .Access.AsCamelCaseField( Prefix.Underscore )                
        .WithForeignKey( &amp;quot;DATASET_ID&amp;quot; )
	.FetchType.Join&lt;/pre&gt;

&lt;p&gt;As you can see from the code we&amp;#160; are trying to setup the mapping to our BusinessUnit entity, and we are providing the foreign key as ‘DataSet_ID’.&amp;#160; However when we generate the .hbm.xml file and run the code it throws the Invalid Column name exception saying that it cannot find BusinesUnit_ID.&amp;#160; &lt;/p&gt;

&lt;p&gt;Here is the .hml.xml snippet for this mapping&lt;/p&gt;

&lt;pre class="xml" name="code"&gt;&amp;lt;many-to-one access=&amp;quot;field.camelcase-underscore&amp;quot; foreign-key=&amp;quot;DATASET_ID&amp;quot; fetch=&amp;quot;join&amp;quot; name=&amp;quot;BusinessUnit&amp;quot; column=&amp;quot;BusinessUnit_id&amp;quot; /&amp;gt;&lt;/pre&gt;

&lt;p&gt;At first glance you may be wondering why it is trying to use BusinessUnit_ID as the column name.&amp;#160; The reason is that FluentNHibernate assumes that the column u are mapping against in the patent is the ‘id’ value of the entity (BusinessUnit_ID).&amp;#160; However, in my case this is not true.&amp;#160; In order to resolve this I simply need to tell FluentNHiberhate what the true column name is.&amp;#160; I can do so with the following code&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;References( x =&amp;gt; x.BusinessUnit )
        .Access.AsCamelCaseField( Prefix.Underscore )                
        .WithForeignKey( &amp;quot;DATASET_ID&amp;quot; )
	.TheColumnNameIs( &amp;quot;DATASET_ID&amp;quot; )
	.FetchType.Join&lt;/pre&gt;

&lt;p&gt;When I run this code, it will generate the following .hbm.xml file&lt;/p&gt;

&lt;pre class="xml" name="code"&gt;&amp;lt;many-to-one access=&amp;quot;field.camelcase-underscore&amp;quot; foreign-key=&amp;quot;DATASET_ID&amp;quot; fetch=&amp;quot;join&amp;quot; name=&amp;quot;BusinessUnit&amp;quot; column=&amp;quot;DataSet_ID&amp;quot; /&amp;gt;&lt;/pre&gt;

&lt;p&gt;So, if you ever find you self with the Invalid column name exception make sure you have completely setup your mappings.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44171" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/FluentNhibernate/default.aspx">FluentNhibernate</category></item></channel></rss>