NHibernate使用QueryOver选择具有相关子对象的对象列表

时间:2017-05-24 07:56:28

标签: c# nhibernate queryover

我遇到的问题可能非常简单。 在我的数据库中,我有以下表格:

tblOrder
-----------------
Id
OrderStatusId

tblOrderStatus
-----------------
Id
Name

我在我的项目中做了以下映射:

[Class(NameType = typeof(Order), Table = "tblOrder")
public class Order {
    [Id(-2, Name = "Id")]
    [Generator(-1, Class = "native")]
    public virtual long Id { get; set; }

    [ManyToOne]
    public virtual OrderStatus Status { get; set; }
}

[Class(NameType = typeof(OrderStatus), Table = "tblOrderStatus")]
public class OrderStatus {
    [Id(-2, Name = "Id")]
    [Generator(-1, Class = "native")]
    public virtual long Id { get; set; }

    [Property]
    public virtual string Name { get; set; }
}

查询应返回IList<OrderSummary>。我希望类OrderSummary具有属性Status,其中Status是具有IdName属性的对象。这可以使用KeyValuePairOrderStatus类型(以最佳和最适合的方式)。获取订单不是问题,但添加OrderStatus作为具有所述属性的对象是我遇到问题的部分。 我还需要将查询结果作为JSON返回给客户端。

OrderSummary应如下所示:

public class OrderSummary {
    public long Id { get; set; }
    public OrderStatus Status { get; set; }
}

在我的第一个版本OrderSummary中有OrderStatusIdOrderStatusName的单独属性。这有效,但我试图避免这些单独的属性。 我也尝试使用SelectSubQuery,但这会返回一个错误,因为它返回子查询中的多个字段。

-----------------------------------更新----------- ------------------

按照Fredy Treboux的建议,我使用Eager更改了我的查询,这导致以下查询:

var query = session.QueryOver<OrderStatus>
    .Fetch(o => o.Status).Eager
    .JoinAlias(o => o.Status, () => statusAlias, JoinType.LeftOuterJoin);

问题是,我发现,不是选择数据,而是如何转换检索到的Status并将其分配给OrderSummary.Status?我尝试过以下方法:

OrderSummary orderAlias = null;
query.SelectList(list => list
    .Select(o => o.Id).WithAlias(() => orderAlias.Id)
    .Select(() => statusAlias).WithAlias(() => orderAlias.Status)
).TransformUsing(Transformer.AliasToBean<OrderSummary>());

-------------------------------- ANSWER -------------- --------------------

正如我在上一次编辑中所说,问题似乎不是OrderStatus的实际选择,而是将其返回给客户端。所以我认为这是我对NHibernate缺乏了解,而不是像[JsonObject]类那样简单地添加OrderStatus属性。我真傻。

我已将查询更改为以下内容:

Order orderAlias = null;
OrderSummary orderSummary = null;
OrderStatus statusAlias = null;
var query = session.QueryOver<Order>(() => orderAlias)
    .JoinAlias(() => orderAlias.Status, () => statusAlias, JoinType.LeftOuterJoin);

query = query
    .Select(
        Projections.ProjectionList()
            .Add(Projections.Property(() => orderAlias.Id).WithAlias(() => orderSummary.Id))
            .Add(Projections.Property(() => orderAlias.Status).WithAlias(() => orderSummary.Status)
    );
Result = query.TransformUsing(Tranformers.AliasToBean<OrderSummary>())
    .List<OrderSummary>()
    .ToList();

2 个答案:

答案 0 :(得分:2)

我担心目前无法做到这一点。我猜Nhibernate变换器无法构造嵌套的复杂属性。 您可以返回元组列表,然后手动将其强制转换为您的实体:

it 'show edit form when a cardex record is clicked' do
      page.find('.link-record-edit', match: :first).click
      page.find('#cardx-edit-form', wait: 50)
      expect(page).to have_selector('#cardx-edit-form')
    end

此外,如果您不太了解性能,可以获取订单列表并将其转换为OrderSummary。您只需定义强制转换运算符或使用AutoMapperExpressMapper等工具即可。

答案 1 :(得分:1)

抱歉,我之前没有看到您的评论要求提供示例。 我将留下一些代码来解释我提到的方法,虽然它已经在其他响应中作为替代方案提供,我相信这是最简单的方法(根本不使用变换器):

string GetOrderSummaries()
{
   // First, you just query the orders and eager fetch the status.
   // The eager fetch is just to avoid a Select N+1 when traversing the returned list.
   // With that, we make sure we will execute only one query (it will be a join).
   var query = session.QueryOver<Order>()
                      .Fetch(o => o.Status).Eager;

   // This executes your query and creates a list of orders.
   var orders = query.List();

   // We map these orders to DTOs, here I'm doing it manually.
   // Ideally, have one DTO for Order (OrderSummary) and one for OrderStatus (OrderSummaryStatus).
   // As mentioned by the other commenter, you can use (for example) AutoMapper to take care of this for you:
   var orderSummaries = orders.Select(order => new OrderSummary
   {
      Id = order.Id,
      Status = new OrderSummaryStatus
      {
         Id = order.Status.Id,
         Name = order.Status.Name
      }
   }).ToList();

   // Yes, it is true that this implied that we not only materialized the entities, but then went over the list a second time.
   // In most cases I bet this performance implication is negligible (I imagine serializing to Json will possibly be slower than that).
   // And code is more terse and possibly more resilient.

   // We serialize the DTOs to Json with, for example, Json.NET
   var orderSummariesJson = JsonConvert.SerializeObject(orderSummaries);
   return orderSummariesJson;
 }

有用的链接:
AutoMapper:http://automapper.org/
Json.NET:http://www.newtonsoft.com/json