Linq-to-Entities查询中的动态条件
我正在尝试将一些直接构建SQL查询的旧代码转换为Entity Framework,并遇到了许多人似乎都有的问题(从围绕该主题的大量问题来判断):如何在linq中表达动态条件。
我怎么能用linq查询表达以下代码:
switch (status) { case "0": sqlwhere = " WHERE status = 0 "; break; } if (strsearch != "") sqlwhere += " AND desc LIKE '%" + strsearch + "%' "; string sqlc = "SELECT top 10 * FROM c " + sqlwhere + " order by date desc";
我在其他post中读过PredicateBuilder
和动态Linq扩展,但我认为像没有外部库的情况下可以解决一个简单的案例。
使用.net 4.5,EF 5.0,C#,这可以以“动态”方式完成,而无需为每个案例构建完整的linq语句吗?
如果您不想使用外部的东西,那么只需使用流畅的API:
var query = db.YourTableName .Where(x => x.desc.Contains(strsearch)); switch (status) { case "0": query = query.Where(x => x.status < 0); break; case "-1": query = query.Where(x => x.status == -1); break; case "-100": query = query.Where(x => x.status == -100); break; case "1": default: query = query.Where(x => x.status >= 0); break; } var result = query.OrderByDescending(x => x.date) .Take(10);
BTW您可以创建按状态过滤的扩展方法。 您的查询将如下所示:
var query = db.YourTableName .FilterByStatus(status) .Where(x => x.desc.Contains(strsearch)) .OrderByDescending(x => x.date) .Take(10);
扩展方法:
public static IQueryable FilterByStatus(this IQueryable query, string status) { switch (status) { case "0": return query.Where(x => x.status < 0); case "-1": return query.Where(x => x.status == -1); case "-100": return query.Where(x => x.status == -100); case "1": default: return query.Where(x => x.status >= 0); } }
在您的情况下,使用PredicateBuilder ,如下所示
另请查看我的博文: 使用Linq进行动态查询
var outer = PredicateBuilder.True(); switch (status) { case "0": outer = outer.And (p => p.status<0); break; case "-1": outer = outer.And (p => p.status==-1); break; case "-100": outer = outer.And (p => p.status==-100); break; case "1": default: outer = outer.And (p => p.status>=0); break; } if (strsearch != "") outer = outer.And (p => p.desc.Contains(strsearch )); dataContext.Entity.Where (outer );
您可以将LinkExtension与LinqKit 一起使用
上述就是C#学习教程:Linq-to-Entities查询中的动态条件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
using (var context = new workEntities() ) { Dictionary> dictionary = new Dictionary>(); dictionary["Title"] = new List { "Network Engineer", "Security Specialist", "=Web Developer" }; dictionary["Salary"] = new List { ">=2000" }; dictionary["VacationHours"] = new List { ">21" }; dictionary["SickLeaveHours"] = new List { "<5" }; dictionary["HireDate"] = new List { ">=01/01/2000", "28/02/2014" }; dictionary["ModifiedDate"] = new List { DateTime.Now.ToString() }; var data = context.Employee.CollectionToQuery(dictionary).ToList(); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1024566.html