开发者

Creating Dynamic Fetch Expression

开发者 https://www.devze.com 2023-03-27 17:50 出处:网络
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,

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

精彩评论

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

关注公众号