Restricting the scope of the query to a single OU with LinqToLdap

This article builds on OrganizationalUnit CRUD, providing more options when creating queries.


One thing you might want to do when searching is limit your search to a single organizationalUnit/container.  You can do this by specifying the SearchScope as a parameter to the query.

Using the project from OrganizationalUnit CRUD, you’ll need to add a reference to System.DirectoryServices.ProtocolsS.DS.P is the technology underlying LinqToLdap and you sometimes need to refer to S.DS.P objects to configure LinqToLdap.

The original version of Program.cs is:

using System;
using System.Linq;
using LinqToLdap;

namespace BlogOuTest1
    class Program
        static void Main(string[] args)
            var config = new LdapConfiguration()
                .AddMapping(new OrganizationalUnitObjectMap());


            var counter = 0;
            var context = new DirectoryContext();

            // ----- Start of section to replace -----
            var ous = context.Query<OrganizationalUnitObject>();

            foreach (var ou in ous)
                Console.WriteLine("Ou: {0}",
            // ----- End of section to replace -----

            Console.WriteLine("Counter = {0}", counter);
            Console.WriteLine("\r\nPress a key to continue...");

with the usual OrganizationalUnitObject.cs and OrganizationalUnitObjectMap.cs files.

On my network, this produces a list of 500 OUs.  At the top level, I have only be twelve OUs and eleven other containers.  To view the twelve OUs, change as follows.

Add the word SearchScope between the parentheses of the line

var ous = context.Query<OrganizationalUnitObject>();

You’ll see a little blue line appear under the first ‘S’:

Some of you will know that this is part of IntelliSense and will give you the option of adding a Namespace or a fully-qualified class name.  Some of you won’t know that instead of hovering over the line and waiting for the menu icon , then hovering over that and waiting for the menu to appear, you can type Shift+Alt+F10 and bring the menu up immediately:

Select the first option, “using System.DirectoryServices.Protocols;” and you should see the following added to the bottom of your list of using statements at the top of the file:

using System.DirectoryServices.Protocols;

Now you can complete the line such that it looks like this:

var ous = context.Query<OrganizationalUnitObject>(SearchScope.OneLevel);

When I run this, I get the expected twelve OUs.

Unfortunately, it doesn’t appear to be possible to specify the source OU in this version of LinqToLdap, so you’re limited to the namingContext specified in the ClassMap (see MadHatter22’s second comment in this thread, at Dec 21 2011 at 2:58 AM).  That functionality is available in the current source code – I’ll blog about it in a future post.

I’ll address the other eleven containers in another article.