2

我有非常简单的 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");
    }
}
4

1 回答 1

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();
于 2013-05-20T09:07:51.510 回答