我設置了三個模型。我不確定我是否以最好的方式做到了這一點,但這是我可以輕鬆理解的方式。我調用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);
}
}
}
幾乎'NullReferenceException'的所有情況都是一樣的。請參閱「[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」的一些提示。 –