Contents tagged with NHibernate
A long, long time ago, I wrote a NHibernateDataSource control. Back then, it was based in the first LINQ provider for NHibernate, and a long has happened since. Now, I decided to give it another go!
Historically, in ASP.NET, a data control should inherit from DataSourceControl, like ObjectDataSource, LinqDataSource, EntityDataSource, SqlDataSource, etc, and should expose collections for parameters for each of the supported operations (select, update, delete and insert). Since ASP.NET 4, however, a new base class came along: QueryableDataSource. This class is an implementation of IQueryableDataSource, which allows using QueryExtender, also introduced in version 4, to filter and sort the results of a data source that uses LINQ.
I wanted my control to be able to use QueryExtender, but I also wanted to be able to give it an HQL query. It should also be capable of inserting, updating and deleting entities.
So, here’s what I came up with, first, the NHibernateDataSource class:
You can see that it exposes some events:
- Configure: gives developers a chance to build (or return an existing) Configuration instance, that will be used for building the session factory;
- BuildSessionFactory: allows setting parameters on the default session factory or returning an existing one;
- CreateInstance: raised before NHibernate creates a default instance, to allow developers to return one;
- EntityInserting: raised before an entity is inserted, allowing developers to cancel the operations or to set entity parameter;
- EntityUpdating: raised before an entity is updated, allowing developers to cancel the operations or to set entity parameter;
- EntityDeleting: raised before an entity is deleting, allowing its cancellation;
- EntitiesSelecting: raised before a select operation is performed;
- EntityInserted: raised after an entity was inserted;
- EntityUpdated: raised after an entity was updated;
- EntityDeleted: raised after an entity was deleted;
- EntitiesSelected: raised after a select operation was performed;
- OperationCompleted: raised after an operation completes (select, insert, update or delete).
If no handler for CreateInstance is supplied, NHibernateDataSource will try to create an entity using Activator.CreateInstance.
EntitySelecting is raised regardless of the Mode (Hql or Linq), but it will have different values in its argument: a query string plus parameters in the case of Hql and an IQueryable instance for Linq.
EntityInserting, EntityUpdating and EntityDeleting allow the modification of properties of the entity in the parameter, but not the replacing of the entity itself.
OperationCompleted is always called, except in the event of an exception.
It also exposes a couple of properties:
- Mode: one of the two operation modes, Hql or Linq. If Hql is used, then the Hql property must be set; otherwise, it’s EntityName that is required;
- Hql: an NHibernate HQL query string;
- EntityName: the name of an entity that the control will work with; only required for Mode Linq or for inserts, updates or deletes;
- RefreshBeforeUpdate: whether NHibernate should refresh the properties of an entity before updating or deleting it;
- MaximumRecords: the optional maximum number of records to retrieve, if paging is not used (PageSize and PageIndex);
- PageIndex: the page index to retrieve;
- PageSize: the page size to retrieve;
- SessionFactory: a session factory that will be used instead of a default created one;
- SelectParameters: a collection of parameters to be applied to the Hql string;
- InsertParameters: a collection of parameters for the insert operation;
- UpdateParameters: a collection of parameters for the update operation;
- DeleteParameters: a collection of parameters for the delete operation.
And, of course, exposes the basic operations: select is the default, but Insert, Update and Delete methods are available.
NHibernateDataSource will check if the SessionFactory property is set, otherwise, it will build its own Configuration instance and raise the Configure and BuildSessionFactory events. The generated session factory is then stored in the InternalSessionFactory static property for caching.
Then, the NHibernateDataSourceView, which is the responsible for the actual querying, inheriting from QueryableDataSourceView:
And the NHibernateDataSourceMode:
Finally, all of the event arguments:
Now, let’s see concrete examples of its usage. First, using Mode Hql:
You can see that the Hql property has a parameter, price, which is bound to a parameter in SelectParameters with the same name. Each parameter is an instance of the Parameter class, here I am using a parameter with a static value (Parameter) and another that takes a value from the query string (QueryStringParameter), but others exist. To help with NHibernate insert and update operations, I created a new Parameter class, EntityParameter, that knows how to retrieve a en entity or a proxy to an entity:
As for Mode Linq, an example using a QueryExtender is in order:
The LINQ query produced by the NHibernateDataSource is intercepted by the QueryExtender and a where (SearchExpression) and a order by (OrderByExpression) clauses are added to it. Other expressions can be used, inheriting from DataSourceExpression, and some take parameters of type Parameter. Do notice that filtering and sorting is performed server-side, not client-side.
Of course, this can certainly be improved, let me hear your thoughts and questions.
And that’s it. Enjoy!
This page will list all of my book reviews, in no particular order.
Right now, I am reviewing Microsoft Azure Development Cookbook Second Edition, just give me some more days, because it’s a long one.
Microsoft Azure Development Cookbook Second Edition
(Review not yet available)
Windows Presentation Foundation 4.5 Cookbook
NHibernate 2 Beginner's Guide
NHibernate 3.0 Cookbook
Visual Studio 2012 and .NET 4.5 Expert Development Cookbook
NHibernate in Action Book
Instant StyleCop Code Analysis How-to Review
Programming Entity Framework
Pro WF: Windows Workflow in .NET 3.5
In case you ever want to have a look at the generated SQL before it is actually executed, you can use this extension method:
Parameters such as 100 will be located in the nhLinqExpression.ParameterValuesByName collection.
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
Suppose you have some properties of an entity, including its id, and you want to refresh its state from the database:
Image is a Byte and is configured as lazy. The problem is that NHibernate is not capable of returning a proxy for it, because the entity itself is not a proxy.
This does not happen for associated entities (one-to-one, many-to-one, one-to-many and many-to-many):
In this case, Customer is another entity, and NHibernate can assign the Order.Customer property a proxy to it.
Because of this problem, I created a simple extension method that loads all properties. It is even smart enough to use proxies, if we so require it:
Of course, it requires that at leat the id property is set. It can be used as:
Just for you to know that the NHibernate community hasn’t been sleeping, here’s a list of some of the cool new features that are on the queue for the next NHibernate versions.
Some are still waiting for review from the NHibernate team and because of that, don’t yet have a target version.
Common base type for ISession and IStatelessSession (NH-1440)
A long-sought request, this will allow abstracting the two kinds of sessions. It is scheduled for NH 5.
IQueryable support for persistent collections (NH-2319)
Allows querying collections without loading them. For NH 5.
Method for specifying IType of LINQ parameter (NH-2401)
Allows one to override the type of a parameter. For NH 4.1.
Allow injectable/inheritance of Linq query provider (NH-2611)
Allows replacing the default LINQ provider for a custom one, which may support additional features. It is scheduled for NH 4.1.
NH cannot load mapping assembly from GAC (NH-2831)
Now we will be able to load assemblies containing mappings from the GAC. For NH 4.0.2.
Optimistic Locking in mapping by code (NH-2823)
Setting the lock mode in a LINQ query, bringing it to pair with the other query APIs. For NH 4.1.
Linq: NHibernateContext for WCF Data Service (NH-2920)
For exposing NHibernate in a WCF Data Service. For NH 5.
Add missing standard Id Generators in Mapping By Code (NH-3404)
All the id generators will now be available in mapping by code. In NH 4.1.
Ability to select the root entity in a criteria projection (NH-3435)
In a Criteria query, it will be possible to select the root entity, from which the query originated. For NH 4.1.
Allow Session.Query to load entities as read-only (NH-3470)
Another functionality that was missing in LINQ API. Will be available in NH 4.1.
Allow query model visitor to be provided through the session factory (NH-3499)
Another extensibility hook. For NH 4.1.
Allow Creating of Child Stateless Session (NH-3606)
Right now, it is only possible to create full stateless sessions from existing ones, this will fix that. For NH 4.1.
Make default value of FlushMode configurable (NH-3619)
Sometimes it is useful to have a specific flush mode specified other than the default for all new sessions created. For NH 4.1.
Strongly Typed Delete (NH-3659)
Delete from a LINQ expression. For NH 5 only.
Support Bulk Inserts (NH-3675)
Allow bulk insertions using each provider’s specific mechanism. For NH 5.
Query by Example in Linq (NH-3714)
Using entities as examples for LINQ queries. Will be available in NH 5.
Handle Information Messages from Server (NH-3724)
Add the ability to handle information messages from the database server (the InfoMessage event). Will be ready in NH 5.
Delete in Criteria and QueryOver (NH-3735)
Delete from an existing Criteria or QueryOver query. Only in NH 5.
Pass Table Variable as a Input parameter to Stored Procedure (NH-3736)
Allows passing table-valued parameters to NHibernate SQL queries in SQL Server. Not scheduled yet.
Sometimes it makes sense to send several queries at the same time to the database server. This prevents multiple roundtrips and normally can provide results faster. Knowing this, NHibernate offers two features: multiqueries and future queries. Future queries build upon multiqueries and because they use LINQ, which is probably the most common querying API in NHibernate, I will focus in this.
In order to use future queries, you queue them, by calling the ToFuture() or ToFutureValue() extension methods on any number of queries that you wish to retrieve together:
Only after you actually access its results are the queries sent:
And the generated SQL is:
Notice how the two queries are sent at the same time, separated by a semicolon.
It also works for single values, they can be combined with multi value queries:
The caveat is that this, like multiqueries, is right now only supported in SQL Server, Oracle and MySQL. In all the other cases the results will be retrieved immediately.
This one is a real treat!
When we use NHibernate or any other O/RM, we normally use classes to represent the database objects (tables or views). In NHibernate, this is called Entity Mode POCO – Plain Old CLR Object. NHibernate, however, supports other Entity Mode: Map. This Entity Mode does not use “physical” classes, but instead, dictionaries (implementations of IDictionary)! This makes it great for mapping dynamic database objects without the need for real classes.
For creating a Map entity, we need to do a slight change in our usual mappings, here is a simple Parent-Child example:
You might not have noticed that I used entity-name instead of name in the <class> declaration, in <one-to-many> and <many-to-one>; this tells NHibernate that these classes will be mapped as Map, not POCO (the default). Alas, you cannot use mapping by code, because there is no physical class to map.
OK, so now we have a mapped Parent and Child. We insert them as this:
As for retrieving, also simple, just use the ISession methods that take an entityName parameter:
Each of these IDictionary instances will have an entry that has key “$type$” and contains the entity type name – in our case, either “Parent” or “Child” – as well as entries for each of the other mapped properties, associations and collections:
Entity Mode Map supports both HQL and Criteria querying APIs:
And it also supports executable HQL:
Cool, don’t you thing? Eat your heart out, Unnamed Framework!
Another not widely known feature of NHibernate: mixing client and server-side calls.
To illustrate this, imagine that you want to calculate the difference between a mapped DateTime property and the current time, DateTime.Now. The following query works in NHibernate, but not in other O/RM frameworks:
The generated SQL will only be:
But NHibernate will detect that the result needs to be combined with something from the client side and will return a TimeSpan. This mechanism is extensible – more on this in a future post.
In other O/RMs, which shall remain unnamed, you have to use LINQ to Objects after LINQ to Unnamed Framework:
Pretty cool, don’t you think?
Today I start a new series on lesser-known NHibernate features.
Besides the normal mapping of a class to a table (or view, for that matter), it is also possible to map a class to a query. Do note that this is not the same as having a class mapped to a table and using custom SQL for the INSERTs, UPDATEs, SELECTs or DELETEs, this is something different. This is called Subselect mapping - not to be confused with subselect fetching.
To demonstrate this, imagine we have a blogging model where a Blog has several Posts. We can map a readonly query between the two as (in HBM.XML):
In mapping by code, it would be:
It easy to understand that the class cannot be mutable: it makes no sense to change any of the properties, because they may not map directly to a table.
Querying is done in exactly the same way:
And the resulting SQL is:
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
When you want to specify an NHibernate type (implementation of NHibernate.Type.IType) for a property using mapping by code, you might be tempted to do something like this:
If you try this, you will get a nasty exception about the type not having a public parameterless constructor. Ouch!
The thing is: NHibernate types are supposed to be stateless, and therefore it does not make sense to have several instances of a type, that is why NHibernate encourages us to use the static fields defined in the NHibernateUtil class and that is also why most of the built-in types don’t have a public parameterless constructor.
So, if you want to implement your own types, you can certainly add a public parameterless constructor to them and use the above syntax, but if you are going to use the built-in types, you should instead use: