我一直在使用几种不同的 tuts 来构建 LINQ-to-LDAP 模型。我刚刚完成它,但我在尝试将返回的数据绑定到类时遇到了一些问题。
我通过将自定义属性分配给作为数据库字段的实际名称的类的属性来执行相反的部分。
这是该类以及自定义属性的示例(不包括DirectorySchemaAttribute
和DirectoryRootAttribute
实现......这些部分工作正常):
[DirectorySchema("C4User"), DirectoryRoot("o=c4, ou=users")]
class User
{
[DirectoryAttribute("cn")]
public string Username { get; set; }
[DirectoryAttribute("userpassword")]
public string Password { get; set; }
[DirectoryAttribute("C4-Parent")]
public string Parent { get; set; }
}
/// <summary>
/// Specifies the underlying attribute to query for in the directory.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class DirectoryAttributeAttribute : Attribute
{
private string attribute;
private DirectoryAttributeType type;
/// <summary>
/// Creates a new attribute binding attribute for a entity class field or property.
/// </summary>
/// <param name="attribute">Name of the attribute to query for.</param>
public DirectoryAttributeAttribute(string attribute)
{
this.attribute = attribute;
this.type = DirectoryAttributeType.Ldap;
}
/// <summary>
/// Creates a new attribute binding attribute for a entity class field or property.
/// </summary>
/// <param name="attribute">Name of the attribute to query for.</param>
/// <param name="type">Type of the underlying query source to get the attribute from.</param>
public DirectoryAttributeAttribute(string attribute, DirectoryAttributeType type)
{
this.attribute = attribute;
this.type = type;
}
/// <summary>
/// Name of the attribute to query for.
/// </summary>
public string Attribute
{
get { return attribute; }
set { attribute = value; }
}
/// <summary>
/// Type of the underlying query source to get the attribute from.
/// </summary>
public DirectoryAttributeType Type
{
get { return type; }
set { type = value; }
}
}
因此,我正在使用属性的 DirectoryAttributeAttribute::Name 值填充我的 LDAP 搜索的属性。如果没有指定,那么我只使用属性的类型名称。所以本质上,User.Username 映射到“cn”等等。
我想知道最好的方法是做相反的事情。因此,如果我得到一个包含名为“cn”的字段的 LDAP 结果,我如何找到具有等于“cn”的 DirectoryAttributeAttribute.Name 的属性。我正在开发一个获取每个属性的自定义属性的 foreach,但是我必须为结果集中的每个字段运行该 foreach :( 有点麻烦。有人能想到更好的方法吗?
这是确定属性映射到的字段名称的函数的代码:
private string GetFieldName(System.Reflection.MemberInfo member)
{
DirectoryAttributeAttribute[] da = member.GetCustomAttributes(typeof(DirectoryAttributeAttribute), false) as DirectoryAttributeAttribute[];
if (da != null && da.Length != 0)
{
if (da[0].Type == DirectoryAttributeType.ActiveDs)
throw new InvalidOperationException("Can't execute query filters for IADs* properties.");
else
return da[0].Attribute;
}
else
return member.Name;
}
谢谢,克里斯