如何在C#中将nhibernate列表转换为IList <T>

问题描述

我有一个来自NHibernate结果集的模型对象列表,希望有一个通用方法将其转换为 IList

我有这个

Cannot convert return expression of type 'AnyPublisher<Publishers.FlatMap<_,Publishers.Map<Publishers.MapError<Publishers.Encode<Just<T>,JSONEncoder>,_>,URLRequest>>.Output,Publishers.FlatMap<_,URLRequest>>.Failure>' (aka 'AnyPublisher<_.Output,_>') 
to return type 'AnyPublisher<Void,Error>'

需要转换为

var l = session.CreatesqlQuery(@query).SetResultTransformer(Transformers.AliasToEntityMap).List();

使得从nhibernate返回的任何List都可以轻松地与任何模型类匹配

我尝试过

IList<T> ls = new List<T>();

但出现错误

List<T> newList = l.Cast<T>().ToList();

其中SalesModel是我的通用模型

也尝试过

system.invalidCastException: Unable to cast object of type 'System.Collections.Hashtable' to type SalesModel 

并收到此错误

var l = session
    .CreatesqlQuery(@query)
    .SetResultTransformer(Transformers.AliasToBean<SalesModel>())
    .List();

IList<SalesModel> newList = l.Cast<SalesModel>().ToList();

这是我的模型课

A first chance exception of type 'NHibernate.PropertyAccessException' occurred in NHibernate.dll
NHibernate.PropertyAccessException: The type System.Decimal can not be assigned to a property of type system.int32 setter of model.SalesModel.total ---> System.ArgumentException: Object of type 'System.Decimal' cannot be converted to type 'system.int32'.

解决方法

问题在于返回的集合l包含类型System.Collections.Hashtable的项目。这是因为您使用的Transformers.AliasToEntityMap表示:

每行结果都是从别名到值/实体的映射(System.Collections.IDictionary)。

要制作类型为SalesModel的物品,您需要使用Transformers.AliasToBean<SalesModel>(),其中:

创建一个结果转换器,该转换器将通过属性方法或字段将别名值注入T的实例中。

然后您可以投射它或改用List<T>()

IList<SalesModel> list = session
    .CreateSQLQuery(@query)
    .SetResultTransformer(Transformers.AliasToBean<SalesModel>())
    .List<SalesModel>();