【问题标题】:How do I page my Active Directory query results?如何分页我的 Active Directory 查询结果?
【发布时间】:2017-03-18 05:45:18
【问题描述】:

我正在为我的组织开发一个基于 Web 的员工电话簿,它使用 C#/AccountManagement 查询 Active Directory 中的数据。我正在尝试查询 AD 并根据返回的用户主体创建“员工”列表。我可以获取所有记录,但出于性能原因希望能够从服务器返回分页结果。我试图在我的 FindAll() 方法上使用 LINQ(Take and Skip),但我遇到的问题是我进一步过滤我的结果以检查空的 GivenName 和 Surname 以摆脱测试帐户等。这最终返回当我尝试 .Take(20) 时的示例 16 结果。这是我第一次尝试在应用程序中使用 AD,我希望有人能指出我正确的方向,希望得到任何建议或批评。下面是数据访问方式:

public static List<Employee> GetAllEmployees()
    {
        List<Employee> employees = new List<Employee>();
        try
        {

            PrincipalContext context = new PrincipalContext(ContextType.Domain, "My Domain");

            GroupPrincipal gp = GroupPrincipal.FindByIdentity(context, "Domain Users");

            UserPrincipal principal = new UserPrincipal(context);

            principal.Enabled = true;
            using (PrincipalSearcher searcher = new PrincipalSearcher(principal))
            {
                searcher.QueryFilter = principal;
                var results = searcher.FindAll();

                foreach (UserPrincipal p in results)
                {
                    if (p.IsMemberOf(gp))
                    {
                        if (p.GivenName != null && p.Surname != null)
                        {
                            string division = string.Empty;
                            DirectoryEntry de = p.GetUnderlyingObject() as DirectoryEntry;
                            if (de.Properties.Contains("department"))
                            {
                                division = de.Properties["department"].Value.ToString();
                            }

                            var employee = new Employee(p.GivenName, p.Surname, p.DisplayName, p.EmailAddress, division);

                            employees.Add(employee);
                        };
                    }
                }

            }

        }
        catch (Exception)
        {

            throw;
        }
        return employees;
    }

【问题讨论】:

  • 那么您的问题是什么?返回 16 有什么问题?
  • @HungCao 假设我有 1000 个用户,我希望能够一次返回 10、20、50、100 来对结果进行分页。如果我在 FindAll() 方法上执行 .Take(20),我的结果将进一步过滤给没有 FirstName 或 LastName 的用户,因此可能返回 16 而不是 20。这是不对的,但我不确定我该怎么做在返回下一个 20、10、50 之前以有效的方式过滤这些结果,无论我需要什么。

标签: c# .net linq active-directory


【解决方案1】:

原来答案很简单,我忽略了。我将过滤移到了 foreach 循环之外。我摆脱了:

if (p.IsMemberOf(gp))

if (p.GivenName != null && p.Surname != null)

并替换为:

principal.GivenName = "*";
principal.IsMemberOf(gp);

在我的循环之前。我现在可以在我的 searcher.Findall() 方法上执行 .Take() 并收到我期望的快速结果。

【讨论】:

    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多