I have using PredicateBuilder
class to dynamically creating Where
clause in LINQ statements.
Following is my code which is When using predicate
var predicate = PredicateBuilder.True<tbl_login>();
predicate = predicate.And(x => x.DAT_LOGIN_TIME >= startDate && x.DAT_LOGIN_TIME <= endDate);`
var data = context.tbl_login.Join(context.tbl_user, x => x.LNG_USER_PRIMARY_ID, y => y.LNG_USER_PRIMARY_ID, (x, y) => new
{
userID = x.LNG_USER_PRIMARY_ID,
loginTime = x.DAT_LOGIN_TIME,
ageGroup = y.INT_AGE_GROUP
}).Where(predicate)
.Select(x => new
{
userID = x.userID,
ageGroup = x.ageGroup
}).Distinct().ToList();
It gives me compile time exception cannot convert from System.Linq.Expressions.Expression<System.Func<JoyRydeAnalysis.Data.tbl_login,bool>>' to System.Linq.Expressions.Expression<System.Func<AnonymousType#1,int,bool>
What i am missing?
Your predicate is a predicate for tbl_login
. But here, you're projecting to an anonymous type:
(x, y) => new
{
userID = x.LNG_USER_PRIMARY_ID,
loginTime = x.DAT_LOGIN_TIME,
ageGroup = y.INT_AGE_GROUP
}
That predicate can't be applied to that projection.
I suspect you may want to apply the predicate earlier instead though:
var data = context.tbl_login
.Where(predicate)
.Join(...)
.Select(...)
.Distinct()
.ToList();
Note that at this point, your Select
will be redundant, as you can just change the projection in the Join
call.
It's also note clear why you're using PredicateBuilder
at all, to be honest. You're only joining PredicateBuilder.True
with a single expression - so you can just use:
var data = context.tbl_login
.Where(x => x.DAT_LOGIN_TIME >= startDate && x.DAT_LOGIN_TIME <= endDate)
.Join(...)
.Select(...)
.Distinct()
.ToList();
See more on this question at Stackoverflow