tags:

views:

1275

answers:

2

Hello

I am fixing a codebase using NHibernate and I found out that instead of using Get or Load to find entities by ID they were using a query.

Like :

session.CreateCriteria(typeof(T)).Add(Expression.AllEq(propertyNameValues)).List<T>();

where the propertyNameValues is a IDictionnary containing "ID" and the id value.

Trying to replace it with :

session.Get<T>(id);

Nhibernate throws a No Persister found for my class.

But there is obviously one as the first method works, my google-fu only found links where it was people forgetting to set the given hbm to embedded ressources or the mapping assembly in the nhibernate configuration.

I tried Get(id) , Get(typeof(T),id), Get("ClassName",id) all throw same error.

Here is the mapping as requested (thank you)

<class name="Domain.Customers.Customer, Domain" table="Customer" lazy ="true">
 <id name="ID" column="id" access="field.lowercase-underscore" type="int">
  <generator class="identity" />
 </id>

This is the mapping of one class but it's generic for all my entitites.

Thanks for any pointer.

A: 

You need to look at the mapping for whatever T is. CreateCriteria is being used to return a range, so Get(id) is unlikely to work.

You could try

Get<Customer>(new Customer(){ ID= id });

but I'd need to see your code to give a better example.

As you've shown in the mapping, the ID field would be the key, but I'm a bit confused by what propertyNameValues in the orginal query is, if it is an array (or similar) of int

you could try

List<Customer> customers = new List<Customer>();
foreach(int idInt in propertyNameValues)
{
   Customer currentCustomer = session.Get<Customer>(idInt);
   customers.Add(currentCustomer);
}

but if you are really looking for it to work with the propertyNameValues dictionary and the dictionary has one item with a key of Id and a value that fits your mapping, then try

session.Get<Customer>(propertyNameValues["Id"]);

Hope this helps.

Mark Dickinson
When I say confused about propertyNameValues, I mean how does it work if the key is always ID? Glad you've got this codebase to fix, not me :)
Mark Dickinson
I mean the "propertyNameValues" is there standard way of doing for other query... like key = "Number" Value = "1234" ... but the method GetByID simply redirect to this method using key = "ID" value = "1". And as posted by Ayende : http://ayende.com/Blog/archive/2009/04/30/nhibernate-ndash-the-difference-between-get-load-and-querying-by.aspxthis is not the good way to do it.
pmlarocque
I think it just boils down to not doing a query to find one item by it's key. If the dictionary only contains one value, then look at refactoring it out. If it contains a range, consider using a query with an Expression.In filter.
Mark Dickinson
A: 

Is "ID" mapped as the identity property for the object? As Mark said, we will need to see the mapping to give a better answer.

Jamie Ide