![](/img/trans.png)
[英]Error:The value “System.Object[]” is not of type “prjCustomerService.clsCustomer” and cannot be used in this generic collection. Parameter name: value
[英]Why CreateSQLQuery throwing exception "The value System.Object[] is not of type and cannot be used in this generic collection"?
我有以下数据库表:
CREATE TABLE A
(
[Id] [INT] IDENTITY (1,1) NOT NULL CONSTRAINT A_P_KEY PRIMARY KEY,
[X] [INT]
)
以下是实体类:
public class A
{
public virtual int Id { get; set; }
public virtual int X { get; set; }
}
以下是映射:
internal class AConfiguration : ClassMapping<A>
{
public AConfiguration()
{
Table("A");
Id(x => x.Id, im =>
{
im.Column("Id");
im.Generator(Generators.Identity);
});
Property(x => x.X, map => map.NotNullable(true));
}
}
以下是我如何调用CreateSQLQuery
:
List<A> lst = null;
using(var session = SessionFactory.OpenSession())
{
lst = session.QueryOver<A>().List<A>().ToList();//This works
var sql = @"SELECT Id, X FROM A";
lst = session.CreateSQLQuery(sql).List<A>().ToList();//This fail
}
如上所示, QueryOver
调用工作正常。 但是CreateSQLQuery
调用失败并出现以下异常:
System.ArgumentException was unhandled
HResult=-2147024809
Message=The value "System.Object[]" is not of type "[....].A" and cannot be used in this generic collection.
Parameter name: value
ParamName=value
Source=mscorlib
StackTrace:
at System.ThrowHelper.ThrowWrongValueTypeArgumentException(Object value, Type targetType)
at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
at NHibernate.Util.ArrayHelper.AddAll(IList to, IList from)
at NHibernate.Impl.SessionImpl.ListCustomQuery(ICustomQuery customQuery, QueryParameters queryParameters, IList results)
at NHibernate.Impl.AbstractSessionImpl.List(NativeSQLQuerySpecification spec, QueryParameters queryParameters, IList results)
at NHibernate.Impl.AbstractSessionImpl.List[T](NativeSQLQuerySpecification spec, QueryParameters queryParameters)
at NHibernate.Impl.SqlQueryImpl.List[T]()
at [....]
InnerException:
为什么CreateSQLQuery
调用抛出异常?
这个问题的答案没有帮助,因为我正在选择表格中的所有列; 该问题涉及选择有限的列。
CreateSQLQuery
API 将返回对象数组System.Object[]
。 例外是尝试将此对象数组与您的实体映射时。
你有两种方法:
手动获取对象数组并映射
您可以使用session.CreateSQLQuery(sql).List<Object[]>()
获取对象数组,并使用您的自定义逻辑进一步映射它。 有关更多详细信息,请参阅此或此资源。
指示 NHibernate 如何映射它
NHibernate 具有称为Transformers
功能。 转换器有助于映射复杂的对象。 您可以使用如下所示的内容:
lst = session.CreateSQLQuery(sql) .SetResultTransformer(Transformers.AliasToBean<A>()) .List<A>() .ToList();
有关更多详细信息,请参阅此资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.