How would i write something like this in linq to entities
sb.Append(" WHERE question.question_isdeleted = 0");
if (catid != 0)
sb.AppendFormat(" AND (CatID IN ({0}))", catsSTR);
if(!string.IsNullOrEmpty(AuthorID))
sb.Append(" AND (question_ownerid = @id)");
i think I just need the syntax to write an if conditional in linq to entities
Yes you can like: var query = someList. Where(a => a == "something"); if (condition) { query = query. Where(b => b == "something else"); } var result = query.
In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below. This is how we can use LINQ where clause filtering operator to filter data based on conditions.
The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.
I would use dot notation here:
var query = questions.Where(q => !q.IsDeleted);
if (catId != 0)
{
query = query.Where(q => cats.Contains(q.CatID));
}
if (authorId != 0)
{
query = query.Where(q => q.OwnerId == authorId);
}
You could write your own extension method to do this slightly more simply:
public static IQueryable<T> OptionalWhere<T>(
this IQueryable<T> source,
bool condition,
Expression<Func<T,bool>> predicate)
{
return condition ? source.Where(predicate) : source;
}
You could then write:
var query = questions.Where(q => !q.IsDeleted);
.OptionalWhere(catId != 0, q => cats.Contains(q.CatID))
.OptionalWhere(authorId != 0, q => q.OwnerId == authorId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With