문제

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.

도움이 되었습니까?

해결책

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 );

다른 팁

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"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top