如何将NHibernate关联查询结果转换为目标模型?报错求助
解决NHibernate QueryOver左关联转模型的报错问题
问题根源分析
你的代码存在3个关键问题导致转换失败:
- 转换器顺序错误:
TransformUsing放在了Select之前,NHibernate需要先确定查询返回的字段集合,才能应用属性映射规则。 - 字段未指定匹配别名:
AliasToBean依赖查询列别名与目标模型GetDfSystemCityDistrict的属性名完全匹配,未指定别名会导致映射失败。 - 关联对象错误:
Left.JoinAlias关联的是外键字段DfSystemCityId,而非实体导航属性,无法正确建立左关联关系。
修正后的代码
假设你的DfSystemDistrict实体(对应districtalias)有导航属性DfSystemCity(关联城市实体cityalias),且GetDfSystemCityDistrict模型包含DistrictName、CityName等属性,修正代码如下:
var query = Session.QueryOver(() => districtalias) // 修正:通过导航属性建立左关联 .Left.JoinAlias(x => x.DfSystemCity, () => cityalias) .Where(y => y.DistrictName == name) // 选择字段并指定与模型属性一致的别名 .Select( Projections.Alias(Projections.Property(() => districtalias.DistrictName), "DistrictName"), Projections.Alias(Projections.Property(() => cityalias.CityName), "CityName") ) // 转换逻辑放在Select之后 .TransformUsing(Transformers.AliasToBean<GetDfSystemCityDistrict>()) .Future<GetDfSystemCityDistrict>(); IList<GetDfSystemCityDistrict> model = query.ToList(); return model;
额外注意事项
- 如果你的实体没有导航属性,只能通过外键关联,可以改用
JoinQueryOver:.Left.JoinQueryOver(() => cityalias, Restrictions.EqProperty("districtalias.DfSystemCityId", "cityalias.Id")) - 确保
GetDfSystemCityDistrict模型有无参构造函数,AliasToBean需要通过无参构造创建实例后赋值。
内容的提问来源于stack exchange,提问作者Emre
相关产品推荐
相关产品推荐

