0

I'm trying to produce a mapping for a class in NHibernate that will map to a query that is hand written to include a field that isn't in the table that the class map relates to.

The table would be as follows:

Id int 
Name varchar(50)
Parent int

The class:

int Id {get; set;} 
string Name {get; set;} 
int ParentId {get; set;}
int ChildCount {get; set;}

The mapping:

x => x.Id, "Id" 
x => x.Name, "Name" 
x => x.Parent, "Parent" 
x => x.ChildCount, "ChildCount"

There is a custom query that returns 'ChildCount' as a property which maps to the class perfectly, the problem arises when the class is used in a relationship with another class and NHibernate loads the class implicitly. Is there a way to specify that the ChildCount mapping should exist but only for binding a query to the class and not for automatically creating the SQL for loading the object straight from the database.

In the latter instance NHibernate fails because it creates an SQL query along the lines of

SELECT Id, Name, Parent, ChildCount FROM ...

where the object is a loaded as part of the relationship.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Orbittman
  • 1
  • 1

1 Answers1

0

You can use the Formula(string formula) method to map this property, and add a sql sub query to do this, for sample:

Map(x => x.ChildCount).Formula("select count(*) from Table where parent=id");

It will result in a sub query to count how many child has, passing the id in the parent column.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194