问题
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;}
}
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");
I know foo
in second statement is really a Bar
because query selects ContainerBar
.
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.
回答1:
var query = from foo in session.Linq<Foo>()
select foo.ContainerBar;
query = query.Where(foo => foo.F1 == "abcdef");
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.
You should do:
var bars = from foo in session.Linq<Foo>()
where foo.F1 == "abcdef"
select foo.ContainerBar;
Or:
var q = session.Linq<Foo>();
// if some condition
q = q.Where( foo => foo.F1 == "abcdef" );
var bars = q.Select( foo => foo.ContainerBar );
回答2:
Are you using NHibernate 3.0? The first query doesn't work for me (NHibernate 2.1.2.4000, invalid cast). However, it looks like you're trying to get all Bars that have Foos, which can be done like this...
IQueryable<Bar> bars = Session
.Linq<Bar>()
.Where(bar => bar.Foos.Any());
Now that you have the Bars, in your later code you can check F1 like this...
var result = bars
.Where(bar => bar.Foos.Any(foo => foo.F1 == "b"));
来源:https://stackoverflow.com/questions/4138093/dynamic-linq-to-nhibernate-query-problem