如何实现admin的过滤搜索

时间:2012-01-11 13:48:22

标签: asp.net linq search filtering

我一直在尝试为我的系统管理员实施搜索页面。长话短说,有3个参数作为标准。 1.用户,2.projects,3。客户。管理员可以对这三个标准进行任意组合。例如“我希望看到分配给这个项目的所有用户以及所有客户”或“我想看到这个客户和这个项目,但所有用户”等等。你如何实现这样的过滤?我正在使用asp.net 4.0和linq以防万一。

这是功能内容,它是全部。我已经通过条件确定了它,但它根本不健康。

public static List<Data.CurrentActivity> GetUsersActivitySearch(string employeeId, string projectId, string customerId, DateTime startDate, DateTime endDate)
        {
            DataClassesDataContext dc = new DataClassesDataContext(General.ConnectionString);

            if(projectId=="" && customerId!="")
              return  dc.CurrentActivities.Where(t => t.User.RecId.ToString() == employeeId && t.Customer.RecId.ToString() == customerId && t.ActivityDate >= startDate && t.ActivityDate <= endDate).ToList();
            else if (projectId != "" && customerId == "")
                return dc.CurrentActivities.Where(t => t.User.RecId.ToString() == employeeId && t.Project.RecId.ToString() == projectId && t.ActivityDate >= startDate && t.ActivityDate <= endDate).ToList();
            else if (projectId != "" && customerId != "")
                return dc.CurrentActivities.Where(t=>t.User.RecId.ToString()==employeeId && t.Customer.RecId.ToString()==customerId && t.Project.RecId.ToString()==projectId && t.ActivityDate>=startDate && t.ActivityDate<=endDate).ToList();
            return dc.CurrentActivities.Where(t => t.User.RecId.ToString() == employeeId && t.ActivityDate >= startDate && t.ActivityDate <= endDate).ToList();
        }

1 个答案:

答案 0 :(得分:0)

现在我看到了你的代码,我有一个简单的解决方案。由于延迟执行,您实际上可以在IQueryable接口上复合where子句:

        DataClassesDataContext dc = new DataClassesDataContext(General.ConnectionString);
        var result = dc.CurrentActivies.Where(t.ActivityDate >= startDate && t.ActivityDate <= endDate);

        if(userId.Length > 0)
            result = result.Where(t => t.User.RecId.ToString() == employeeId);

        if (projectId.Length > 0)
            result = result.Where(t => t.Project.RecId.ToString() == projectId);

        if (customerId.Length > 0)
            result = result.Where(t=>t.Customer.RecId.ToString()==customerId);

        return result.ToList();

如果您有一个可以表示足够信息以显示结果的通用对象。然后你可以做这样的事情:

public IList<SearchResults> Search(string user, string customer, string project)
{
    return (from user in context.Users
        where SqlMethods.Like(user.Name, user) && user.Length > 0
        select new SearchResult
        {
            ... properties you care about
        })
        .Concat(from project in context.Projects
             where SqlMethods.Like(project, project.Name) && project.Length > 0
             select new SearchResult
             {
                 ///
             })
        .Concat(from customer in context.Customers
             where SqlMethods.Like(customer, customer.Name) && customer.Length > 0
             select new SearchResult
             {
                 ///
             })
        .ToList();
}