看時,我有很簡單的LINQ表達式:NHibernate的查詢拋出異常,通過相關表格
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");
}
}
你是如何映射Order實體?並做任何其他查詢工作? – JTMon
已更新的問題。 – VikciaR
你說其他查詢正在工作,所以不知道是否是這樣,嘗試添加一個表格元素到映射文件,包括表格名稱[](表格(「[Order]」)) – JTMon