我一直在使用几种不同的方法来构建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; }
}
}
因此,我使用Property的DirectoryAttributeAttribute :: Name值填充LDAP搜索的属性。如果没有指定,那么我只使用Property的Type名称。所以实质上,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;
}
谢谢, 克里斯