Querying AD using LinqToLdap

There are several ways to return results from LinqToLdap (documented here).  I prefer the ClassMap approach because it gives me POCOs which I can use with WCF RIA Services.  Since I’ll probably be using them for most of my posts, I’ll start with a ClassMap here.

All you need to make this work is a console project and a reference to LinqToLdap.dll from Version 2.0.2 of LinqToLdap, the name of your Domain Controller or the dns name of your domain in this line:


and the defaultNamingContext of your domain (or an OU distinguishedName, if you want to restrict the search) in this line:


at least, it will if you’ve an account with a common name starting “John”.

using System;
using System.Collections.ObjectModel;
using System.Linq;
using LinqToLdap;
using LinqToLdap.Mapping;

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

            var context = new DirectoryContext();

            var users = context.Query<UserObject>()
                .Where(u => u.commonName.StartsWith("John"));

            foreach (var user in users)
                Console.WriteLine("User ID: {0,-12}\t\tCN: {1}",

            Console.WriteLine("\r\nPress a key to continue...");

    public class UserObjectMap : ClassMap
        public UserObjectMap()
            DistinguishedName(x => x.distinguishedName);
            Map(x => x.commonName).Named("cn");
            Map(x => x.description);
            Map(x => x.displayName);
            Map(x => x.employeeID);
            Map(x => x.objectGuid).StoreGenerated();
            Map(x => x.otherTelephone);
            Map(x => x.sAMAccountName);
            Map(x => x.userAccountControl);
            Map(x => x.whenChanged).StoreGenerated();
            Map(x => x.whenCreated).StoreGenerated();

    public class UserObject
        public Guid objectGuid { get; set; }
        public String commonName { get; set; }
        public String distinguishedName { get; set; }
        public String employeeID { get; set; }
        public String sAMAccountName { get; set; }
        public String description { get; set; }
        public String displayName { get; set; }
        public Collection<String> otherTelephone { get; set; }
        public Int32 userAccountControl { get; set; }
        public DateTime whenCreated { get; set; }
        public DateTime whenChanged { get; set; }

Good luck.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: