我正在使用事件目录获取所有部门并使用 linq 查询过滤不同的部门,下面是我的代码
private static DomainController GetDomainController(string domainpath)
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath);
var domain = Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
return controller;
}
private static MyMethod()
{
var domainController = GetDomainController(ActiveDirectorySettings.DomainPath);
// Lookup the information in AD
var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind };
DirectorySearcher ds;
ds = new DirectorySearcher(ldapEntry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))"
};
ds.PropertiesToLoad.Add("department");
if (ds.FindAll().Count >= 1)
{
//DataSet du = DataReader.CheckAdUserExist();
var results = ds.FindAll();
var uniqueSearchResults = results.Cast<SearchResult>().Select(x => GetProperty(x,"department")).Distinct();
addUsersList.AddRange(uniqueSearchResults.Select(departmentName => new UsersAndDepartments
{
UserDepartment = departmentName
}));
}
}
我想用数据库检查linq查询结果是否已经存在部门,我不知道该怎么做?
最佳答案
如果您想要使用 SqlConnection
创建一个简单的数据库连接,您只需使用从 AD 请求中收到的 department
参数查询您的数据库。
try{
SqlConnection connection = new SqlConnection("YourConnectionstring");
connection.Open();
//Your connection string can be found through your Server DB
//Now you go through your SearchResultCollection populated by SearchResult objects
foreach(SearchResult res in uniqueSearchResult){
SqlCommand cmd = new SqlCommand("Select * from yourTable where department=" +res.Properties["department"][0].ToString() + "", connection);
SqlDataReader reader = cmd.ExecuteReader();
//Here you verify if there are corresponding rows in your table
//with the request you have executed
if(!reader.HasRows()){
//If you have not found corresponding rows, then you add the department to your
//list
addUsersList.Add(res.Properties["department"][0].ToString());
}
}
connection.close();
}catch(Exception e){
Console.WriteLine("Exception caught : \n\n" + e.ToString();
}
这应该有效。
有很多这方面的教程,但是如果您提出很多请求,我不建议您使用这种连接方法,您只会浪费太多时间/组织,也许可以尝试使用像 Entity Framework 这样的持久性框架:
https://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
希望这能回答您的问题!
关于c# - 如何检查针对 Sql Server 数据库的 linq 查询结果是否存在数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44718019/