从父母中选择子投影

时间:2010-02-15 16:56:37

标签: linq-to-nhibernate

以下是我网域中的三个类:

public class Quote : IEntity, IAggregateRoot {
    public int QuoteId { get; set; }
    public IEnumerable<Price> Prices { get; set; }
}

public class Price : IEntity {
    public int PriceId { get; set; }
    public Carrier Carrier { get; set; }
    public decimal? Price { get; set; }
    public Quote Quote { get; set; }
}

public class Carrier : IEntity, IAggregateRoot {
    public int CarrierId { get; set; }
    public string Name { get; set; }
}

我希望能够根据报价中的价格选择投影。返回类型应该是IEnumerable&lt; [匿名对象]&gt;。我必须从Quote开始查询,因为它是根域对象。以下是我到目前为止的情况:

session.Linq<Quote>()
    .Expand("Prices")
    .Where(q => q.QuoteId == 1)
    .Select(q => {
        //this is where I don't know what to do.
        //Maybe somthing like this:
        return q.Prices.Select(p => {
            new { CustomerName = p.Customer.Name, Price = p.Price }
        });
    });

映射将是:

  • Quote.Prices&gt; HasMany(一对多)
  • Price.Quote&gt;参考文献(多对一)
  • Price.Carrier&gt;参考文献(一对一)

1 个答案:

答案 0 :(得分:2)

我找到了答案。我完全忘记了SelectMany Linq表达式。这是我的解决方案。

session.Linq<Quote>()
    .Where(q => q.QuoteId == 1)
    .SelectMany(q => q.Prices, (q, p) => new { CustomerName = p.Customer.Name });