我有一个基本的NHibernate.Linq查询:
var items = from item in session.Linq<ObjectType>()
where item.ID > 0
select new { ID = item.ID, Type = item.ClassName };
这很好用。但是,ObjectType是一个重量级的类,我只想要ID和ClassName。所以我创建了一个名为EntityInfo
的DTO:
public class EntityInfo
{
public String ID { get; set; }
public String Type { get; set; }
}
我想要返回IEnumerable<EntityInfo>
:
return from item in session.Linq<ObjectType>()
select new EntityInfo() { ID = item.ID.ToString(), Type = item.ClassName };
尝试迭代返回的IEnumerable时,我得到以下异常:
System.ArgumentOutOfRangeException : Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) at System.ThrowHelper.ThrowArgumentOutOfRangeException() at System.SZArrayHelper.get_Item[T](Int32 index) at System.Collections.ObjectModel.ReadOnlyCollection`1.get_Item(Int32 index) at NHibernate.Linq.Visitors.SelectArgumentsVisitor.VisitMethodCall(MethodCallExpression expr) at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp) at NHibernate.Linq.Visitors.NHibernateExpressionVisitor.Visit(Expression exp) at NHibernate.Linq.Visitors.ExpressionVisitor.VisitList(ReadOnlyCollection`1 original) at NHibernate.Linq.Visitors.ExpressionVisitor.VisitNew(NewExpression nex) at NHibernate.Linq.Visitors.SelectArgumentsVisitor.VisitNew(NewExpression expr) at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp) at NHibernate.Linq.Visitors.NHibernateExpressionVisitor.Visit(Expression exp) at NHibernate.Linq.Visitors.RootVisitor.HandleSelectCall(MethodCallExpression call) at NHibernate.Linq.Visitors.RootVisitor.VisitMethodCall(MethodCallExpression expr) at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp) at NHibernate.Linq.Visitors.NHibernateExpressionVisitor.Visit(Expression exp) at NHibernate.Linq.Visitors.NHibernateQueryTranslator.Translate(Expression expression, QueryOptions queryOptions) at NHibernate.Linq.NHibernateQueryProvider.TranslateExpression(Expression expression) at NHibernate.Linq.NHibernateQueryProvider.Execute(Expression expression) at NHibernate.Linq.Query`1.GetEnumerator()
select语句中是否不允许ToString()
?我通过运行原始查询,然后通过手动将匿名类型映射到EntityInfo
实例来创建新的可枚举,但我显然更喜欢以前的版本。
作为参考,我使用的是NHibernate.Linq 1.0.0.4000,NHibernate 2.1.0.4000和FluentNHibernate 1.0.0.593。
答案 0 :(得分:1)
你的意思是使用对象初始化器而不是数组初始化器吗?
return from item in session.Linq<ObjectType>()
select new EntityInfo() { ID = item.ID.ToString(), Type = item.ClassName };
答案 1 :(得分:0)
我对.ToString()
有同样的问题,似乎在LINQ-to-NHibernate查询中不允许这样做。我的解决方法不只是比较数值。对于您的问题,我建议使用以下类和查询:
public class EntityInfo
{
private String _id;
public int ID {
get {return _id.ToString();}
set {_id = Convert.ToInt32(value);};
}
public String Type { get; set; }
}
return from item in session.Linq<ObjectType>()
select new EntityInfo() { item.ID, item.ClassName };