NHibernate,在表之间连接并返回特定类型

时间:2012-11-07 20:05:12

标签: c# entity-framework nhibernate orm

我有2个表,我想在结果类中放置一些字段,但是我被卡住了。我想要的代码与Entity Framework一样:

var res =   
(from p in context.EstimationItem
    join q in ...
    select new EstimationWithDetail
    {
        Estimation = q.Estimation,
        Id = q.Id,
        FullName = q.Customer.FirstName + q.Customer.LastName

    }).ToList();

在Nibernate,此时,我有这个,但我被卡住了......

var res =
    Session.QueryOver<EstimationItem>()
    .JoinQueryOver(x => x.Estimation)
    .Select(
        x => x.Estimation.Reference,
        x => x.Estimation.CreationDate,
        x => x.Price,
        x => x.Estimation.Customer.FirstName,
        x => x.Estimation.Customer.LastName
        )
    .List();

public class Estimation
{
    public virtual string Reference { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual DateTime CreationDate { get; set; }
    public virtual decimal Total { get; set; }
    public virtual IList<EstimationItem> EstimationItems { get; set; }
}

public class EstimationItem
{
    public virtual decimal Price { get; set; }
    public virtual int Quantity { get; set; }
    public virtual Estimation Estimation { get; set; }
    public virtual Product Product { get; set; }
}

public class EstimationWithDetail
{
    public string Reference { get; set; }       //Estimation.Reference
    public string FullName { get; set; }        //concat FirstName and LastName from Customer
    public decimal Price { get; set; }          //Estimation.Total
    public int Id { get; set; }                 //Estimation.Id
    public DateTime CreationDate { get; set; }  //Estimation.CreationDate
}

更新1

我尝试了代码,但是我收到了这个错误: InvalidOperarionException,从范围''引用的'EstimationItem'类型的变量'x',但未定义

var res =
    Session.QueryOver<EstimationItem>()
    .JoinQueryOver(x => x.Estimation)
    .Select(x => new EstimationWithDetail
    {
        Code = x.Estimation.Reference,
        CreationDate = x.Estimation.CreationDate,
        Price = x.Estimation.Total,
        FullName = x.Estimation.Customer.FirstName + x.Estimation.Customer.LastName
    })
    .List<EstimationWithDetail>();

更新2: 我也试过这个

Estimation a = null;
Customer b = null;
var res = Session.QueryOver<EstimationItem>()
    .JoinAlias(c => c.Estimation, () => a)
    .JoinAlias(c => c.Estimation.Customer, () => b)
    .Select(x => new EstimationWithDetail
    {
        Code = a.Reference,
        Id = a.Id,
        FullName = b.LastName
    })
    .List<EstimationWithDetail>();

1 个答案:

答案 0 :(得分:0)

我对NHibernate的Linq提供程序不是很熟悉,因为我还没有使用它,但你不能这样做:

var res = Session.QueryOver<EstimationItem>()
    .JoinQueryOver(x => x.Estimation)
    .Select(x => new EstimationWithDetail
    {
        Estimation = x.Estimation,
        Id = x.Id,
        FullName = x.Estimation.Customer.FirstName + x.Estimation.Customer.LastName

    })
    .List();