问题
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
回答1:
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);
回答2:
You can conditionally build a query like this:
var query = from q in questions
where q.question_isdeleted
select q;
if(!string.IsNullOrEmpty(AuthorID))
{
query = from q in query
where q.question_ownerid == AuthorID
select q;
}
However, LINQ to Entities have no good construct that resembles the SQL IN operator...
回答3:
where question.question_isdeleted = 0
&& (catid != 0
? catsStr.Contains(CatId.ToString())
: question_ownerId == id)
Not sure if the string operations are correct, but the logic looks correct.
来源:https://stackoverflow.com/questions/1443152/linq-if-statement