Linq动态OR条件

时间:2015-09-21 10:56:07

标签: c# linq entity-framework-6 dynamicquery

我有这样的用户表,

Id(int)
Name(string),
State_Id(Int64),
Country_Id(Int64),
MobileNumber(String),
email(String),
identity(String)
Role_Id
Disable(Boolean)

标识列将以逗号分隔,例如(手中的痣,面部中的痣)。此值是预定义的,

现在我有这样的请求,

class UserRequest
{
public String RoleName{get;set;}
public String CountryName{get;set;}
publi String StateName{get;set;}
publi IList<String> identityLst{get;set;}
}

使用我想要形成查询的请求。

public IList<User> GetUser(UserRequest req)
{

 IQueryable<User> query=dataContext.user.where(a=>!a.isdisable)
 if(String.IsNullOrEmpty(req.RoleName))
 {
  query=from qu in query
      from role in datacontext.role.where(a=>a.id==qu.role.id)
      where role.name==req.RoleName
      select qu;
}

if(String.IsNullOrEmpty(req.CountryName))
{
query=from qu in query
      from country in datacontext.country.where(a=>a.id==qu.country.id)
      where country.name==req.CountryName
      select qu;
}

if(String.IsNullOrEmpty(req.StateName))
{
query=from qu in query
      from state in datacontext.state.where(a=>a.id==qu.state.id)
      where state.name==req.StateName
      select qu;
}

if(req.identityLst!=null)
{
/////Here I need a query with or condition, Is it possible. 
/////for example if identity List have 3 value. i need a 3 or condition 
}
}

请帮我解决这个问题, 如果identityLst有10个值,那么我将达到DB 10次。

1 个答案:

答案 0 :(得分:-1)

不要在服务器上以qry的形式进行,而是在运行时进行一些后期过滤。

public IList<User> GetUser(UserRequest req){
    //remove the [if(req.identityLst!=null)] part
}

public bool ContainsIdentity(IList<string> x, IList<string> y)
{
    if( x == null || y == null ) return false;
    return x.Any(test => y.Contains(test));
}

var users = GetUser(req).ToList();
var filtered = users.Where( u => ContainsIdentity(u.identity.Split(','), req.identityLst ));