Question

I have pretty simple linq expression:

session.Query<Order>().Where(x => x.States.OrderByDescending(z => z.Date).FirstOrDefault().Name == "2").ToList();

Result: InvalidCastException Unable to cast object of type 'Antlr.Runtime.Tree.CommonTree' to type 'NHibernate.Hql.Ast.ANTLR.Tree.IASTNode'.

Same query with LinqPad works as expected: selects orders, which last state is OnTheWay. How can I circumvent this and get desired result?

Code to try yourself:

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");
    }
}
Était-ce utile?

La solution

After some time research I found solution:

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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top