我设置了三个模型。我不确定我是否做得最好,但这是我可以轻松理解的方式。我调用DepartmentProfile
类。找到的第一个用户不是经理,因此它进入 else 语句并成功填写AD_UserProfile
并添加到DepartmentProfile
类中。
第二个用户是部门经理,因此它进入 if 语句并在第一行出错,对象未设置为对象实例。我错过了什么?我没有正确设置模型吗?
当它出错时
public class AD_UserProfile
{
public string distinguishedName { get; set; }
public string email { get; set; }
public string manager { get; set; }
public string name { get; set; }
public string userPrincipalName { get; set; } // Useful if we need to allow a user to 'log on' as a different user.
public string userName { get; set; }
}
public class AD_ManagerProfile
{
public string distinguishedName { get; set; }
public string email { get; set; }
public string manager { get; set; }
public string name { get; set; }
public string userPrincipalName { get; set; } // Useful if we need to allow a user to 'log on' as a different user.
public string userName { get; set; }
}
public class AD_DepartmentProfile
{
public AD_DepartmentProfile()
{
this.AD_UserProfile = new HashSet<AD_UserProfile>();
}
public string name { get; set; }
public virtual AD_ManagerProfile AD_ManagerProfile { get; set; }
public virtual ICollection<AD_UserProfile> AD_UserProfile { get; set; }
}
这是类的调用:
public void GetDepartmentInfo(string department, string owner = "jeremy")
{
DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = ("(&(objectCategory=person)(objectClass=User)(department=" + department + "))");
ds.SearchScope = SearchScope.Subtree;
AD_DepartmentProfile dp = new AD_DepartmentProfile();
dp.name = department; // assign department name
foreach (SearchResult temp in ds.FindAll())
{
if (owner == temp.Properties["sAMAccountName"][0].ToString())
{
//Current user is manager of department
dp.AD_ManagerProfile.distinguishedName = temp.Properties["distinguishedName"][0].ToString(); // This line errors out with instance not set to object error.
dp.AD_ManagerProfile.email = temp.Properties["mail"][0].ToString();
dp.AD_ManagerProfile.manager = temp.Properties["manager"][0].ToString();
dp.AD_ManagerProfile.name = temp.Properties["name"][0].ToString();
dp.AD_ManagerProfile.userPrincipalName = temp.Properties["userPrincipalName"][0].ToString();
dp.AD_ManagerProfile.userName = temp.Properties["sAMAccountName"][0].ToString();
}
else
{
//Current user is in department and does not manage it
AD_UserProfile p = new AD_UserProfile();
p.distinguishedName = temp.Properties["distinguishedName"][0].ToString();
p.email = temp.Properties["mail"][0].ToString();
p.manager = temp.Properties["manager"][0].ToString();
p.name = temp.Properties["name"][0].ToString();
p.userPrincipalName = temp.Properties["userPrincipalName"][0].ToString();
p.userName = temp.Properties["sAMAccountName"][0].ToString();
dp.AD_UserProfile.Add(p);
}
}
}