0

I have a following code to create an expression:

Expression<Func<Process, bool>> exp = null;

if (condition)
{
    exp = x => x.Hierarchy.StartWith(hierarchy) && x.Level == 2;
}
/*
   other conditions that modify the exp variable
*/
else
{
    exp = x => x.Hierarchy == hierarchy && x.Level == 3;
}

This query can be a diferent according with some conditions. I will use this expression in the following query, but, I would like to concat the exp expression variable in the linq query, for sample:

var query = from p in queryable
            join c in confQueryable on p.Id equals c.Id
            where p.ParentId == parentProcessId && exp // AND exp here...
            let hasChild = p.Processes.Any()
            select new ViewModel
            {
               Code = p.Code,
               Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable
               ParentId = p.Id,
               Value = p.Id.ToString(),
               HasChildren = hasChild, // use hasChild variable
            };

I cannot convert it to linq methods because I return a ViewModel not the entity. If I do it, I do not know how to use the join and let commands in linq methods.

This query will be executed in database with NHibernate.

How could I concat the Expression<Func<T, bool>> in a Linq query?

Thank you.

1 Answer 1

1

Why you can't use chain methods like this

var query =
    queryable
        .Where(exp)
        .Join(confQueryable, p => p.Id, c => c.Id, (p, c) => new {p, c})
        .Where(@t => p.ParentId == parentProcessId)
        .Select(@t => new {@t, hasChild = p.Processes.Any()})
        .Select(@t => new ViewModel
        {
            Code = p.Code,
            Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable
            ParentId = p.Id,
            Value = p.Id.ToString(),
            HasChildren = hasChild, // use hasChild variable
        });

I don't know about nHibernate, but for Entity Framework such linq query should work.

Sign up to request clarification or add additional context in comments.

2 Comments

I can use methods without problem. When I try to Where(exp) it says to me that it cannot be valid because the Where method is waiting the Expression<Func<anonymous type, bool>>, and my expression if Expression<Func<Process, bool>>. Is there a way? Thank you
It should depends on chain. Originally in my answer Where(exp) was after Join, so it was used anonymous object. But I updated it and moved Where before Join. Seems that there is nothing that needed from Join in that exp. Can you try again updated sample?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.