ClassMap 看起来像这样:
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);
}
}
对存储过程的调用如下所示:
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();
}
AddEntity 调用说明要将结果映射到哪个 Entity 类,它将使用上面定义的 ProductCategoryNavigationMap:
.AddEntity(typeof(ProductCategoryNavigation))
如果您仔细查看“sql”变量的值,您会看到两个参数:
- :PortalId
- :LocaleId
这些是通过调用:
.SetInt32("PortalId", portalId)
.SetInt32("LocaleId", localeId)
然后调用.List<ProductCategoryNavigation>()
为我们提供了一个 IList,它允许我们使用 LINQ 来投影我们想要的任何东西。在这种情况下,我得到一个 NavigationViewModel 列表,它目前与 ProductCategoryNavigation 相同,但可以根据需要独立于实体进行更改。
我希望这可以帮助其他刚接触 NHibernate 的开发人员!