[英]linq-to-entity dynamic queries
I'am currently migrating our old system to .Net and I encountered this problem. 我目前正在将旧系统迁移到.Net,我遇到了这个问题。 I want to return the result but I still need to refine it after the function, but using this code, I don't have a choice but to call the result from the database and filter an in-memory result instead which is poor performance.
我想返回结果,但我仍然需要在函数之后对其进行优化,但是使用这段代码,我没有选择,只能从数据库调用结果并过滤内存中的结果而不是性能不佳。
public IQueryable<User> GetUser(string[] accessCodes)
{
string condition = "";
if (accessCodes == null)
{
condition = " AccessCode IS NOT NULL "
}
else
{
for (int i = 0; i <= accessCodes.Length - 1; i++)
{
condition += " AccessCode LIKE '%" + accessCodes[i].ToString() + "%' ";
if (i + 1 <= code.Length - 1)
{
condition += " OR ";
}
}
}
return context.ExecuteQuery<User>("SELECT * FROM User WHERE " + condition, null).ToList();
}
I've tried this approach this but i'm stuck: 我尝试过这种做法,但我被困住了:
public IQueryable<User> GetUser(string[] accessCodes)
{
IQueryable<User> basequery = from u in context.User
select u;
if (accessCodes == null)
{
basequery = basequery.Where(n => n.AccessCode != null);
}
else
{
for (int i = 0; i <= accessCodes.Length - 1; i++)
{
// what am I supposed to do here?
}
}
return basequery;
}
I'm hoping that there are solutions which do not require third party libraries. 我希望有解决方案不需要第三方库。
You can try with Any
: 您可以尝试使用
Any
:
else
{
output = output.Where(u => accessCodes.Any(a => u.AccessCode.Contains(a)));
}
or you can use PredicateBuilder
: 或者您可以使用
PredicateBuilder
:
if (accessCodes == null)
{
output = output.Where(u => u.AccessCode == null);
}
else
{
var predicate = PredicateBuilder.False<User>();
for (int i = 0; i <= accessCodes.Length - 1; i++)
{
predicate = predicate.Or(u => u.AccessCode.Contains(accessCodes[i]))
}
output = output.Where(predicate);
}
I also changed your if
part: Where
method does not modify source, it returns new query definition, so you have to assign it back to output
to make it work. 我还更改了你的
if
部分: Where
方法不修改source,它返回新的查询定义,所以你必须将它分配回output
才能使它工作。
This should work for you: 这应该适合你:
IQueryable<User> basequery = from u in context.User
select u;
if (accessCodes == null)
{
basequery = basequery.Where(u => u.AccessCode != null);
}
else
{
basequery = basequery.Where(u => accessCodes.Contains(u=>u.AccessCode));
}
also make sure you return basequery
, since output
in your method is not defined and not used. 还要确保返回
basequery
,因为方法中的output
未定义且未使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.