LINQ TO SQL如何实现动态查询???

梦在旅途 2014-08-27 01:11:29
LINQ TO SQL如何实现动态查询,也就是类似SQL查询拼接的模式!
之所以想实现在这样功能,主要是考虑到多条件查询,查询的字段及内容都不是确定的
哪位高手有做过,还请指教,谢谢!
...全文
441 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
宝_爸 2014-08-28
  • 打赏
  • 举报
回复
有库的 System.Linq.Dynamic Project Description Extends System.Linq.Dynamic to support Execution of Lambda expressions defined in a string against Entity Framework or any provider that supports IQueryable. I originally came across this source code on Scott Guthrie's Blog while searching for a mechanism to execute dynamic linq statements against entity framework. While this code partially fulfilled my need both it and the assembly System.Linq.Dynamic.dll available for download from NuGet lacked the exact functionality I required. Specifically it did not allow me to execute a full lambda expression represented as a string against my entity objects. In addition it lacked support for Take and Union as well as many other extension functions, though these were the only two with which I was interested. As a consequence I extended the code to support these features. I thought my efforts might benefit someone else so I have decided to host it on codeplex. The original code is licensed under Ms-PL and in accordance with this license the derived codebase I have created is licensed similarly. http://dynamiclinq.codeplex.com/
effun 2014-08-28
  • 打赏
  • 举报
回复

public Person[] QueryPersons(string name, int? gender)
{
  MyDataContext dc = new MyDataContext();
  IQueryable<Person> q = dc.Persons;

  if (!String.IsNullOrEmpty(name))
    q = q.Where(person => person.Name.Contains(name));

 if (gender.HasValue)
    q = q.Where(person => person.Gender = gender);

  return q.OrderBy(person => person.Name).ToArray();
}
threenewbee 2014-08-27
  • 打赏
  • 举报
回复
google dynamic linq 使用这个库,可以把查询写成类似sql那样的字符串,以及得到dynamic结果的查询。
  • 打赏
  • 举报
回复
引用 楼主 wheeky 的回复:
LINQ TO SQL如何实现动态查询,也就是类似SQL查询拼接的模式! 之所以想实现在这样功能,主要是考虑到多条件查询,查询的字段及内容都不是确定的, 哪位高手有做过,还请指教,谢谢!
首先,查询是可以“自身跟自身”组合的。毕竟是延迟执行的,而Linq to SQL 和 SQL Server 系统都会分别对查询先进性几十种可能性的分析,最后只取最优化的查询计划去执行。 不过最重要地是,你为啥不同时使用 ADO.NET 呢?为什么刚学会用两天什么 Linq to SQL 就不用了 ADO.NET 了呢?真是没有长性啊,学什么都是半途而废。跟那种抱着ADO.NET 不敢去尝试 LINQ Provider的人有什么两样呢?
wind_cloud2011 2014-08-27
  • 打赏
  • 举报
回复
查询字段与查询内容不明确的情况下,不好操作,应该是通过前期的条件判断来确定查询条件与内容吧
梦在旅途 2014-08-27
  • 打赏
  • 举报
回复
引用 2 楼 duanzi_peng 的回复:
参见:http://kb.cnblogs.com/page/42489/
这个实现比较复杂,效率可能不高,文中介绍的是WHERE一字段,那如果多个字段又该如何操作呢?有没有简单而高效的方法,在查询字段与查询内容不明确的情况下,实现LINQ动态查询是否可行? 若在知道查询字段的情况下,我是知道如何做,可以用别人封装好的一个类:PredicateExtensions
全栈极简 2014-08-27
  • 打赏
  • 举报
回复
可以连续的加Where条件。
exception92 2014-08-27
  • 打赏
  • 举报
回复
ysd_xwl 2014-08-27
  • 打赏
  • 举报
回复
将查询条件放在一个字符串里,用的时候改变字符串的内容就可以了

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧