动态 linq-to-nhibernate 查询问题 [英] Dynamic linq-to-nhibernate query problem

查看:36
本文介绍了动态 linq-to-nhibernate 查询问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下类 FooBar:

Suppose I have classes Foo and Bar as follow:

public class Foo
{
public string F1 {set; get;}
public string F2 {set; get;}

public Bar ContainerBar {set; get;}
}

public class Bar
{
public string B1 {set; get;}
public string B2 {set; get;}

public List<Foo> Foos {set; get;}
}

以下 linq 查询出现错误,指出 foo 不包含名为 F1 的属性.

Following linq query has errors saying that foo does not contain a property named F1.

var query = from foo in session.Linq<Foo>()
                 select foo.ContainerBar;

query = query.Where(foo => foo.F1 == "abcdef");

我知道第二个语句中的 foo 确实是一个 Bar,因为查询选择了 ContainerBar.

I know foo in second statement is really a Bar because query selects ContainerBar.

问题是知道如何在不更改原始查询的情况下添加动态 where 子句进行查询?最终目标是使用 linq-to-nhibernate 进行子查询.

The question is know how can I add a dynamic where clause to query without changing origianl query? Final goal is to have sub-queries with linq-to-nhibernate.

推荐答案

var query = from foo in session.Linq<Foo>()
                 select foo.ContainerBar;

query = query.Where(foo => foo.F1 == "abcdef");

您的查询"对象现在是 ContainerBar 的 IQueryAble因此,当您执行 Where( foo => foo.F1 == "abcdef" ) 时,它是在 IQueryable 上完成的,因此没有 F1 属性.

Your "query" object is now an IQueryAble of ContainerBar's So when you do the Where( foo => foo.F1 == "abcdef" ), it's done on IQueryable, so no F1 property.

你应该这样做:

var bars = from foo in session.Linq<Foo>()
            where foo.F1 == "abcdef"
            select foo.ContainerBar;

或者:

var q = session.Linq<Foo>();

// if some condition
q = q.Where( foo => foo.F1 == "abcdef" );

var bars = q.Select( foo => foo.ContainerBar );

这篇关于动态 linq-to-nhibernate 查询问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆