The ClassMap looks like this:
public sealed class ProductCategoryNavigationMap : ClassMap<ProductCategoryNavigation>
{
public ProductCategoryNavigationMap()
{
ReadOnly();
// Set "CategoryId" property as the ID column. Without this,
// OpenSession() threw an exception that the configuration was invalid
Id(x => x.CategoryId);
Map(x => x.CategoryNodeId);
Map(x => x.ParentCategoryNodeId);
Map(x => x.Name);
Map(x => x.Title);
Map(x => x.SeoUrl);
// The column name returned from the sproc is "VisibleInd",
// so this is here to map it to the "IsActive" property
Map(x => x.IsActive).Column("VisibleInd");
Map(x => x.DisplayOrder);
Map(x => x.ProductCount);
}
}
The call to the stored procedure looks like this:
public List<NavigationViewModel> GetNavigationViewModel(int portalId, int localeId)
{
const string sql = "EXEC [dbo].[Stored_Procedure_Name] @PortalId=:PortalId, @LocaleId=:LocaleId";
return _session.CreateSQLQuery(sql)
.AddEntity(typeof(ProductCategoryNavigation))
.SetInt32("PortalId", portalId)
.SetInt32("LocaleId", localeId)
.List<ProductCategoryNavigation>()
.Select(x => new NavigationViewModel
{
CategoryId = x.CategoryId,
CategoryNodeId = x.CategoryNodeId,
ParentCategoryNodeId = x.ParentCategoryNodeId,
Name = x.Name,
Title = x.Title,
SeoUrl = x.SeoUrl,
IsActive = x.IsActive,
DisplayOrder = x.DisplayOrder,
ProductCount = x.ProductCount
})
.ToList();
}
The AddEntity calls says what Entity class to map the results to, which will use the ProductCategoryNavigationMap defined above:
.AddEntity(typeof(ProductCategoryNavigation))
If you look carefully at the value of the "sql" variable, you'll see two parameters:
- :PortalId
- :LocaleId
Those are set by making calls to:
.SetInt32("PortalId", portalId)
.SetInt32("LocaleId", localeId)
Then the call to .List<ProductCategoryNavigation>()
provides us with an IList, which allows us to use LINQ to project whatever we want. In this case I'm getting a List of NavigationViewModel, which is currently the same as ProductCategoryNavigation but can change independently of the entity as needed.
I hope this helps other developers new to NHibernate!