开发者

Creating Dynamic Fetch Expression

Creating Dynamic Fetch Expression

I have an object graph like this. I would like to dynamically build fetch expression in Linq to NHibernate so that I get all object graph in one SQL call,

I think, I can write fetch like this, which would do that job,

IQueryable<Customer> lists = customerPersister.Query()
        .Where(item => item.Id == id)
        .FetchMany(item => item.LineOfBusiness)
        .FetchMany(i2 => i2.Address)
        .FetchMany(i3 => i3.Orders)
        .ThenFetchMany(i4=>i4.OrderItems) ;

But I don't need all th开发者_StackOverflow社区ese object graph always. Sometime I need Customer and Address, sometime Customer and LinesOfBusiness or sometime Customer and Orders.

Is there anyway, I can dynamically build this fetch expression?


You should be able to simply expand the query as needed:

IQueryable<Customer> lists = customerPersister.Query().Where(item => item.Id == id);
if (needLinesOfBusiness)
    lists = lists.FetchMany(item => item.LineOfBusiness);
if (needAddress)
    lists = lists.FetchMany(item => item.Address);
if (needOrders || needOrderItems)
{
    if (!needOrderItems)
        lists = lists.FetchMany(item => item.Orders);
    else
        lists = lists.FetchMany(item => item.Orders).ThenFetchMany(order => order.Items);
}

The only trick is that ThenFetchMany doesn't work on an IQueryable<Customer>, so you need to include the order and the order items in one go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜