关于MetadataType,我有一个问题。我有DLL帮助项目,用于使用LinqToSQL从访问数据。我还需要为生成的类ClientInfoView添加元数据。我是这样做的:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace DataAPI.LINQToSQL
{
[MetadataType(typeof(ClientInfoViewMetaData))]
public partial class ClientInfoView
{
internal sealed class ClientInfoViewMetaData
{
[Category("Main Data"), DisplayName("Client ID")]
public int ID { get; set; }
[Category("Main Data"), DisplayName("Login")]
public string Login { get; set; }
...
}
}
}但是当我在运行时检查属性时,我发现ClientInfoView没有任何属性。
你能帮我找个错误吗?
发布于 2013-07-26 06:50:28
为了给出部分答案,您可以检查ClientInfoView是否有属性。一些对我有用的小演示。仍然试图找出为什么我不能访问ClientInfoViewMetaData单独属性中的那些属性
static void Main(string[] args)
{
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(ClientInfoView), typeof(ClientInfoViewMetaData)), typeof(ClientInfoView));
ClientInfoView cv1 = new ClientInfoView() { ID = 1 };
var df = cv1.GetType().GetCustomAttributes(true);
var dfd = cv1.ID.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), true);
var context = new ValidationContext(cv1, null, null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject( cv1,context, results, true);
}
}
[MetadataType(typeof(ClientInfoViewMetaData))]
public partial class ClientInfoView
{
public int ID { get; set; }
public string Login { get; set; }
}
public class ClientInfoViewMetaData
{
[Required]
[Category("Main Data"), DisplayName("Client ID")]
public int ID { get; set; }
[Required]
[Category("Main Data"), DisplayName("Login")]
public string Login { get; set; }
}发布于 2014-07-15 11:51:02
因为元数据类型并不适用于这类组件,但是您可以使用此方法。
private bool PropertyHasAttribute<T>(string properyName, Type attributeType)
{
MetadataTypeAttribute att = (MetadataTypeAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(MetadataTypeAttribute));
if (att != null)
{
;
foreach (var prop in Type.GetType(att.MetadataClassType.UnderlyingSystemType.FullName).GetProperties())
{
if (properyName.ToLower() == prop.Name.ToLower() && Attribute.IsDefined(prop,attributeType))
return true;
}
}
return false;
}你可以这样用
bool res = PropertyHasAttribute<ClientInfoView>("Login", typeof(DisplayAttribute))这告诉您类属性登录有或没有显示属性,但是如果需要查找属性值,可以使用Attribute.GetCustomAttribute方法将其转换为所选属性,如.Name :)显示属性和读取名称属性。)
https://stackoverflow.com/questions/17873576
复制相似问题