Ehsan
Ehsan

Reputation: 3491

Subquery in Linq to NHibernate

I have a query by Linq in NHibernate 3.1:

public IList<Person> Search()
{
    var sub_q = SessionInstance.Query<Person>().Where(x => x.Id < 6).Select(x => x.Id);

    var q = SessionInstance.Query<Person>();
    q = q.Where(x => sub_q.Contains(x.Id));

    return q.ToList<Person>();
}

Id column is primary key in Database This sub-query does not work. Count of my query with sub-query equals by count of my query without use sub-query.

Count of my query whit sub-query : 52 //Correct count is 5

Count of my query without sub-query : 52

Why?

Updated: My problem resolved by rename x variable in sub_q to xx

 var sub_q = SessionInstance.Query<Person>().Where(xx => xx.Id < 6).Select(xx => xx.Id);

Why?

Upvotes: 3

Views: 3239

Answers (2)

Ehsan
Ehsan

Reputation: 3491

My problem resolved by rename x variable in sub_q to xx

 var sub_q = SessionInstance.Query<Person>().Where(xx => xx.Id < 6).Select(xx => xx.Id); 

x in subquery override by x in query. By change it's name, my problem is resolved.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

Apply ToList method on sub_q might resolve your issue because there might be a problem of linq differed execution..

code is like

var sub_q = SessionInstance.Query<Person>()
                   .Where(x => x.Id < 6).Select(x => x.Id).ToList(); 
    var q = SessionInstance.Query<Person>();    
 q = q.Where(x => sub_q.Contains(x.Id)); 

OR you can try

q = q.Where(x => (SessionInstance.Query<Person>()
                 .Where(x => x.Id < 6).Select(x => x.Id)).Contains(x.Id)); 

not sure about above second soltuion

but i think you must need to do ToList() to resolve issue of differed execution..

Upvotes: 2

Related Questions