I need to dynamically add named queries to the NHibernate configuration object. The search engines return few hits referencing NamedSQLQueryDefinition or NamedQueryDefinition. Below is what I'm attempting to do. I don't know what to provide to the NamedSQLQueryDefinition constructor to successfully create a query. Can anyone provide a sample of how to create a new NamedSQLQueryDefinition the right way? Thanks!!
Session initializer:
private static ISessionFactory CreateSessionFactory()
{
var configuration = new Configuration();
return Fluently.Configure(configuration.Configure())
.ExposeConfiguration(AddQueries)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
.Mappings(m => m.HbmMappings.AddFromAssemblyOf<Program>())
.BuildConfiguration()
.BuildSessionFactory();
}
The AddQueries would look something like this:
private static void AddQueries(Configuration cfg)
{
var nameQuery = new NamedSQLQueryDefinition("exec pr_GETCustomer ?", ...)
cfg.NamedSQLQueries.Add("pr_GETCustomer", nameQuery);
var cust = cfg.GetClassMapping(typeof (Customer));
cust.LoaderName = "pr_GETCustomer";
}
PS: I'm trying this route because Fluent NHibernate does not implement a way to configuring the loader & sql-query elements from the hbm file.
I'm pretty new to this but most of the parameters look to be determinable from the attributes you can provide in the HBM file. That said, I'm not too sure what QuerySpaces are. The closest I've got to what I think you are trying to achieve is to use the following (untested):
Obviously, I don't like the cast to SqlQueryImpl. I'm hoping that, once one of us has done it once, obscure properties like querySpaces can be understood, so you won't have to.
Not that I expect it to 100% work, but it may be more achievable from here.
The AddQueries method would be implemented as follows below to "fix" the Fluent NHibernate lack of Loader support. The trick is to properly set up the INativeSQLQueryReturn[] value to contain the mapping from the table columns to the entity properties. It should mimic the contents of the return element of sql-query in the HBM file where the class (with namespace) and property mappings are defined (see XML below). Thanks to @jimbobmcgee for getting me started in this direction!
Sample HBM file that does the same thing: