Linq to sql 实现多条件的动态查询(方法一)
2016-05-10 17:22
806 查看
多条件动态查询在开发中太常见了,使用sql语句拼接很容易实现,但是在使用linq 的时候我却觉得很麻烦,思来想去,其实不然,linq 实现多条件动态查询一样可以变的很简单。话不多说,直接上例子,供大家参考。
根据5个动态条件查询:
[csharp] view
plain copy
print?
/// <summary>
/// Linq to sql 多字段动态查询
/// </summary>
/// <returns></returns>
private List<TVacant> ViewBinding(ModelDataContext db,string fyno,string brd,string area,string city,string pos)
{
Expression<Func<TVacant, bool>> expr = n => GetCondition(n,fyno,brd,area,city,pos);
var xQuery = db.TVacant.Where<TVacant>(expr.Compile());
return xQuery.ToList<TVacant>();
}
private bool GetCondition(TVacant tb,string fyno,string brd,string area,string city,string pos)
{
bool boolResult = true;
if (!String.IsNullOrEmpty(fyno))
{
boolResult &= tb.fy_no == fyno;
}
if (!String.IsNullOrEmpty(brd))
{
boolResult &= tb.brd_no == brd;
}
if (!String.IsNullOrEmpty(area))
{
boolResult &= tb.area_no == area;
}
if (!String.IsNullOrEmpty(city))
{
boolResult &= tb.city_no == city;
}
if (!String.IsNullOrEmpty(pos))
{
boolResult &= tb.pos_no == pos;
}
return boolResult;
}
根据5个动态条件查询:
[csharp] view
plain copy
print?
/// <summary>
/// Linq to sql 多字段动态查询
/// </summary>
/// <returns></returns>
private List<TVacant> ViewBinding(ModelDataContext db,string fyno,string brd,string area,string city,string pos)
{
Expression<Func<TVacant, bool>> expr = n => GetCondition(n,fyno,brd,area,city,pos);
var xQuery = db.TVacant.Where<TVacant>(expr.Compile());
return xQuery.ToList<TVacant>();
}
private bool GetCondition(TVacant tb,string fyno,string brd,string area,string city,string pos)
{
bool boolResult = true;
if (!String.IsNullOrEmpty(fyno))
{
boolResult &= tb.fy_no == fyno;
}
if (!String.IsNullOrEmpty(brd))
{
boolResult &= tb.brd_no == brd;
}
if (!String.IsNullOrEmpty(area))
{
boolResult &= tb.area_no == area;
}
if (!String.IsNullOrEmpty(city))
{
boolResult &= tb.city_no == city;
}
if (!String.IsNullOrEmpty(pos))
{
boolResult &= tb.pos_no == pos;
}
return boolResult;
}
相关文章推荐
- mysql权限管理(实例)
- MongoDB国内学术研究(部分)
- OrmLite数据库框架的集成及使用
- mysql默认可以跨库,mysqli不可以
- oracle text
- CentOS7 yum安装配置 +redis主从配置
- 使用Entity Framework CodeFirst模式创建新数据库
- Oracle中执行存储过程call和exec区别
- Oracle-PL/SQL使用
- Xtrabackup备份数据库
- 数据仓库中的SQL性能优化 - Hive篇
- Sql server 中暂停与恢复主键自增
- MYSQL 5.7 主从复制 -----GTID说明与限制 原创
- Sqlserver2008相关配置问题
- Oracle权限管理详解(转载)
- Oracle、MYSQL、sql server和DB2分页查询写法
- Oracle、MYSQL、sqlserver和DB2分页查询
- Mysql 安全
- mysql 远程连接不上 %用户已经添加了
- memcached原理