动态LINQ到休眠查询问题

动态LINQ到休眠查询问题

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

问题描述

假设我有以下类FooBar:

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.

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

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'sSo 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到休眠查询问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 00:41