我如何在 linq toEntity 中写这样的东西
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)");
我想我只需要在 linq toEntity 中编写 if 条件的语法
我会在这里使用点表示法:
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);
}
您可以编写自己的扩展方法来更简单地执行此操作:
public static IQueryable<T> OptionalWhere<T>(
this IQueryable<T> source,
bool condition,
Expression<Func<T,bool>> predicate)
{
return condition ? source.Where(predicate) : source;
}
然后你可以写:
var query = questions.Where(q => !q.IsDeleted);
.OptionalWhere(catId != 0, q => cats.Contains(q.CatID))
.OptionalWhere(authorId != 0, q => q.OwnerId == authorId);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)