首页 > 技术文章 > .netLinq动态Where条件

tianranhui 2019-03-27 14:37 原文

文章介绍全网最佳方式使用EF+Linq实现多条件组合查询;代码中没有使用到网上主流自定义Expression表达式而是采用linq原生态功能编写示例直观、易懂,且有效解决自定义Expression不支持EF问题。

一、EF+Linq代码片段示例如下(注意只是片段,如果对EF熟悉可轻松理解,model变量为数据模型,MainContext 继承DbContext) :

说明:用IQueryable<tbDevice> table可以初始化null,也可以用var table=XXXX方式,具体视代码结构

IQueryable<tbDevice> table = null;
using (MainContext db = new MainContext())
{
//默认查询所有
table = from t in db.Device
select t;

//下面是多条件组合查询
if (model.Id > 0)
{

table = from t in table
where t.id == model.Id
select t;
}
if (model.GroupId > 0)
{
table = from t in table
where t.groupId == model.GroupId
select t;
}

if (!string.IsNullOrEmpty(model.Name))
{
table = from t in table
where t.name.Contains(model.Name)
select t;
}
if (!string.IsNullOrEmpty(model.SerialNo))
{
table = from t in table
where t.serialNo.Contains(model.SerialNo)
select t;
}

//排序

table = from t in table
orderby t.id descending
select t;

//此处才开始执行查询数据库并返回列表

result.data = table.ToList();
}


string _UserID = string.Empty;
_UserID = "E351D301-F64B-412C-B9EF-573F41235AF2";

string _UserName = string.Empty;
_UserName = "admin";

string _employyName = string.Empty;
_employyName = "测试1";

using (var xj = new XJGasBottles_testDataContext())
{
//Linq写法
var usersLinq = from us in xj.Users
where (string.IsNullOrEmpty(_UserID) || us.UserID.ToString() == _UserID)
&& (string.IsNullOrEmpty(_UserName) || us.UserName == _UserName)
|| (us.EmpName == _employyName)
//where string.IsNullOrEmpty(_UserID) || us.UserID.ToString()==_UserID
//where string.IsNullOrEmpty(_UserName) || us.UserName==_UserName
select us;
foreach (var item in usersLinq)
{
Console.WriteLine("Linq:");
Console.WriteLine(item.UserID + "_" + item.UserName);

}

//Lamda写法
var usersLamda = xj.Users.Where(s => (string.IsNullOrEmpty(_UserID) || s.UserID.ToString() == _UserID) &&
(string.IsNullOrEmpty(_UserName) || s.UserName == _UserName) ||
(s.EmpName==_employyName)
)
.Select(s => s);

foreach (var item in usersLamda)
{
Console.WriteLine("Lamda:");
Console.WriteLine(item.UserID + "_" + item.UserName);

}

}

 

推荐阅读