我有非常简单的linq表达式:
session.Query<Order>().Where(x => x.States.OrderByDescending(z => z.Date).FirstOrDefault().Name == "2").ToList();
结果:InvalidCastException无法将类型为“Antlr.Runtime.Tree.CommonTree”的对象强制转换为“NHibernate.Hql.Ast.ANTLR.Tree.IASTNode”。
LinqPad的相同查询按预期工作:选择订单,最后一个状态是OnTheWay。我怎样才能绕过这个并获得理想的结果呢?
尝试自己的代码:
class Program
{
static void Main(string[] args)
{
ISessionFactory sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(x => x.FromConnectionStringWithKey("defaultConnectionStringForNhibernate")))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetEntryAssembly()))
.BuildSessionFactory();
var session = sessionFactory.OpenSession();
var res2 =
session.Query<Order>().Where(x => x.States.OrderByDescending(z => z.Date).FirstOrDefault().Name == "2").ToList();
}
}
public class Order
{
public virtual int Id { get; set; }
public virtual IList<OrderState> States { get; set; }
public virtual string Name { get; set; }
}
public class OrderState
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime Date { get; set; }
public virtual Order Order { get; set; }
}
public class OrderMap : ClassMap<Order>
{
public OrderMap()
{
Id(x => x.Id)
.GeneratedBy.Identity();
HasMany(x => x.States)
.Inverse()
.AsBag()
.KeyColumn("OrderId");
Map(x => x.Name)
.Not.Nullable();
Table("Orders");
}
}
public class OrderStateMap : ClassMap<OrderState>
{
public OrderStateMap()
{
Id(x => x.Id)
.GeneratedBy.Identity();
References(x => x.Order)
.Column("OrderId");
Map(x => x.Name)
.Not.Nullable();
Map(x => x.Date)
.Not.Nullable();
Table("OrderStates");
}
}
答案 0 :(得分:2)
经过一段时间的研究后,我找到了解决方案:
var res = (from i in session.Query<Order>()
where ((from s in i.States
orderby s.Date descending
select s.Name).First()) == "2"
select i).ToList();