Null !== Steve

Steve Gentile's Tech Blog – Thoughts and Musings

Archive for the category “NHibernate”

New NHibernate.Linq – to be part of NHibernate assembly

Steve Strong has posted an update:

http://nhforge.org/blogs/nhibernate/archive/2009/12/17/using-the-new-linq-to-nh-provider-and-migrating-from-the-old-one.aspx

It is in the trunk now:

http://nhibernate.svn.sourceforge.net/viewvc/nhibernate/trunk/nhibernate/src/NHibernate/Linq/

Learn more about this provider here:

http://nhforge.org/blogs/nhibernate/archive/2009/12/17/linq-to-nhibernate-progress-report-a-christmas-gift.aspx

 

Sorry for not much detail besides the links, but this is pretty big news for Linq and NHibernate.  I have been reading progress reports from Steve for quite awhile now – saw some code in a trunk ~4 months ago that looked very promising then, so it’s great to see these updates.  Awhile back Ayende posted on EF vs. NH, etc… and two things popped out: good Linq support and a good GUI to creating mapping files.  I think this is the Linq support we have been waiting for.

Re-Linq Update

Re-Linq… the ‘better Linq’   :)

The re-motion team has updated their blog with some information on re-linq:

http://www.re-motion.org/blogs/team/archive/2009/09/04/59.aspx#feedback

Additionally, Steve Strong, who is working on the NHibernate re-linq provider, he has an updated progress report (9/15/09):

http://blogs.imeta.co.uk/sstrong/archive/2009/09/15/756.aspx

Good stuff  — who knows, might make for a good Christmas present  :)

Clarification of NHibernate ‘Update’ – used to ‘Attach’

Some of the wording on the NHibernate Session functions can be a tad misleading, or hard to understand.  One is ‘Update’, Update in many ways should be called ‘Attach’!  So, let’s review what Update does:

Session.Update

This sounds like something you call to ‘save’ something right?  Actually it’s not.  The ‘save’ occurs on Save/Commit/Flush.  ie.

using var tran = new Transaction
  Order order = Session.GetById(…)
  order.Updated = true;
  Session.Update(order)     <— not needed
tran.Commit()

Update is actually for ‘tracking’ – not saving.  Let’s say you have an object that is detached from a session – by calling Update on that object will tell NHibernate to start tracking the object again.

ie let’s say we get Order from the HttpSession…

Order order = Session[“Order”] as Order;
Session.Update(order)
tran.Commit()

So, in summary ‘Update’ is for re-associating an object back to the the NHibernate session.   Here is the catch as well – it is telling NHibernate that it is expecting it to be ‘saved’.  You can use Lock and define a LockMode to tell NHibernate that a ‘save’ might not be required.

In a test simulating a n-tier environment, I did detach (Evict) the object, then call ‘Update’ and ‘Lock’, it was able to save the object.  I plan on seeing how to work with optimistic concurrency.

What I find interesting is how badly Linq to Sql appears to handle this vs. NHibernate.  This is what I’m researching at the moment, so if anyone has advice in this area let me know.

NHibernate 2.1and NHibernate Linq 1.0 Released

NHibernate 2.1 has been released

Read more here

Ayende also announces the RTM of NHibernate Linq 1.0  – this is fantastic news!

A couple of items with NH Linq to keep in mind:

This Linq release support just about anything that you can do with the criteria API. We do not support group joins or subqueries in select clauses, since they aren’t supported by the criteria API. NHibernate’s Linq support has been tested (in production!) for the last couple of years, and most people find it more than sufficient for their needs.

https://sourceforge.net/projects/nhibernate/files/NHibernate/2.1.0.GA/NHibernate.Linq-1.0.0.GA-bin.zip/download

As FYI, NHibernate.Linq includes the NHibernateContext class that supports the IUpdateable and IExpandProvider interfaces required by ADO.NET Data Services (thanks Shawn)

More on NCommon

Once again, I’m going to talk about NCommon.  I want to share some of Ritesh Rao’s posts on concepts that NCommon incorporates.  I’m very impressed with his architecture and it helps that he provides NCommon for NHibernate, Linq2Sql, Entity Framework (and I see he is venturing into EF v2).

My last post touched on this, but I’ll review it again:

  1. Framework for implementing a Unit of Work Pattern
  2. Framework for implementing a Repository pattern that utilizes Linq
  3. Framework for implementing a Validations and Business Rules
  4. Implementation of the Specification pattern using Expressions
  5. Utility class to help store application specific data in the Thread Local Storage / Current Web Request and AppDomain Level Storage
  6. Guard class that mimics common guard statements that verify parameter values and throws exceptions if values are not acceptable.

NCommon uses the Apache License 2.0

NCommon uses the  Microsoft.Practices.ServiceLocation – this allows you to plug in your dependency inversion container of choice.  

I have gotten rid of the generic IoC wrapper implementation from the library as it doesn’t seem necessary anymore with the rally behind the Common Service Locator project.

This is shown in the accompany tests setup:

[SetUp]
        public void SetUp()
        {
            EFUnitOfWorkFactory.SetObjectContextProvider(() =>
            {
                var context = new TestModel();
                return context;
            });
            var locator = MockRepository.GenerateStub<IServiceLocator>();
            locator.Stub(x => x.GetInstance<IUnitOfWorkFactory>())
                   .Return(new EFUnitOfWorkFactory()).Repeat.Any();
            ServiceLocator.SetLocatorProvider(() => locator);
        }

NCommon sets the object context and implements the IUnitOfWorkFactory (the above shows with Entity Framework).

An example of how this is used can be found in the UnitOfWorkScopeTransaction class (UnitOfWorkScopeTransaction.cs- trunk/NCommon/src/Data)

ie. the ‘GetTransactionForScope’ method to retrieve the UnitOfWorkFactory:

 
var factory = ServiceLocator.Current.GetInstance<IUnitOfWorkFactory>();
var newTransaction = new UnitOfWorkScopeTransaction(factory, isolationLevel);
newTransaction.AttachScope(scope);
CurrentTransactions.Add(newTransaction);
return newTransaction;
 

The NCommon tests highlight the features of NCommon as well, including Fetching Strategies, Specification, Repositories, and Unit of Work.

Let’s look at some of Ritesh’s posts…

http://www.codeinsanity.com/2009/04/repository-pattern-thoughts.html

Some key items in this post to quote:

repositories should really represent a queryable data store that doesn’t abstract away queries behind methods that some unfortunate developer has to maintain and evolve, but rather allow consumers of the repository to query it directly. Hence why NCommon relies on repositories to implement the IQueryable interface to provide a query infrastructure directly on top of NCommon repositories.

I think this is an important piece to understand, and Ritesh follows up with the comment:

The approach I would take is rather than exposing the infrastructure requirements in the query object, I’d like it to take in an IQueryable and return back a IQueryable. This will allow chaining of queries by multiple of such Query objects without exposing any infrastructure concerns.

…

The problem with exposing ICriteria, or any other infrastructure component, to all layers of the application is that eventually a lot of infrastructure concern creeps into layers of the application where they don’t belong. I dislike the idea of having the expose ICriteria to the UI for adding paging and sorting on top of the query encapsulated by ICriteria.

That being said, in my opinion IQueryable is best suited for this job. Its a framework level member that is infrastructure agnostic, provides a very nice way to chain queries together and encapsulates our query requirements rather well.

Read more…

NHibernate Validator

Ayende has posted about the NHibernate Validator

I’ve been using a custom validator library (that uses attributes like this one).  However, seeing what the NHibernate validator provides, I’d stick with it – since the validation is called on save on the dev behalf.

Ayende also shows how to pull out the errors.

As per his post, you can read the documentation on the library for further information.

As always, good stuff from Ayende!

Windor WCF Integration…bump!

Mike Hadlow’s blog has a great writeup on using Castle Windsor with WCF.

http://mikehadlow.blogspot.com/2008/11/windsor-wcf-integration.html

Also included is information on using WCF with Windsor/NHibernate:

http://mikehadlow.blogspot.com/2009/02/wcf-windsor-integration-using.html

I followed his advice, pulled down his sample code, and was quickly able to implement in my WCF services.  Thanks Mike!

NHibernate MultiCriteria

Today I ran across an interesting problem – I needed to query to get counts after a process runs.  Obviously I can make two database calls, but I instead wanted to take advantage of NHibernate’s ‘MultiCriteria’ capability.  This will make one call to the database with the 2 queries vs. 2 database calls.  My example:

 

IMultiCriteria crit = NHibernateSession.Current.CreateMultiCriteria()
                .Add(CreateCriteria<CompanyDeposit>()
                    .Add(Restrictions.Between("ProcessedDate", lo, hi))
                    .SetProjection(Projections.RowCount()))
                .Add(CreateCriteria<EmployeeDeposit>()
                    .Add(Restrictions.Between("ProcessedDate", lo, hi))
                    .SetProjection(Projections.RowCount()));
            IList results = crit.List();
            var companies = (IList)results[0];
            var employees = (IList) results[1];

            var companyCount = (int)companies[0];
            var employeeCount = (int) employees[0];

 

 

One queries CompanyDeposits and gets the rowcount, the other queries EmployeeDeposits and gets it’s rowcount.

Slick…

For reference, check out Ayende’s post here as well 

(and thanks to Stefan for asking me about it, which made me want to go try it out… lol)

NHibernate – AutoGenerated Identity on a Non-Key Field

We have a requirement to store an additional auto-incremented id to support a legacy app upgrade.  Our primary key is a GUID – the old system used ints, and the client still wants to have that int id – as they use it, etc…

So, within NHibernate we were able to add the following to the property:

property name="GroupId" type="int" generated="always" insert="false" />
 
Thats it.
 
 

NHibernate 2.0.0 GA (note on NHibernate.Linq)

Good news from the NHibernate Team:

NHibernate 2.0.0.GA has been released today:

https://sourceforge.net/project/showfiles.php?group_id=73818&package_id=73969

Regarding the status of NHibernate.Linq:

From Tuna on the NH mailing list:

If you use releases, then it is better you don’t go for linq because there is no release for it and never will be until after 2.1

I suggest you to go and compile it yourself and make it compile if it doesn’t. The patch would be appreciated.

BTW, the contrib version will be have less interest because we want to concentrate on the new implementation and nowadays we can’t find enough time to deal with it.

 

Note as well – this release does not include a dialect for SQL 2008.

 

Update: I’ve decide to refactor out my ‘NHibernate.Linq’ code and replace it with ICriteria queries.  I had to refactor this before with moving away from the NHibernate Query Generator setup I had to NHibernate.Linq.  I decided having the 2.0.0 GA release was worth having now for stability, etc… and to bypass the NHibernate.Linq.  I kept all my queries, as perhaps in the future I would put them back in. 

Working directly with ICriteria has it’s advantages (as well as some disadvantages), but it feels a bit closer to the bone, which tends to mean I have more control over the queries, however I do like being able to the ‘II’ and ‘&&’ operators  :)

Post Navigation

Follow

Get every new post delivered to your Inbox.