Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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"));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top