最近在项目里加了表格组件Grid.MVC
该组件使用很方便,只是需要定义DataAnnotation
因为项目是Database First所以模型类是自动生成的,如果把DataAnnotation写在模型类里面就会被代码生成器覆盖掉。
所以使用了MetadataType Annotation和Partial Class将Annotation和模型类的代码分离开。
但是Grid.MVC不识别在MetadataType Annotation里面定义的Annotation。
没办法下载了源代码,发现这里
public static T GetAttribute<T>(this PropertyInfo pi)
{
return (T) pi.GetCustomAttributes(typeof (T), true).FirstOrDefault();
}
这是取属性的DataAnnotation的代码,里面只检查了CustomAttributes,也就是直接写在属性上方的Attribute
MetadataType里加入的Annotation需要用另外的方法来取
改成这样
public static T GetAttribute<T>(this PropertyInfo pi)
{
T custAttr = (T)pi.GetCustomAttributes(typeof(T), true).FirstOrDefault();
if (custAttr == null)
{
var Attrs = pi.DeclaringType.GetCustomAttributes(typeof(MetadataTypeAttribute), true);
if (Attrs.Length < 1) return default(T);
var metaAttr = Attrs[0] as MetadataTypeAttribute;
var metaProp = metaAttr.MetadataClassType.GetProperty(pi.Name);
if (metaProp == null) return default(T);
custAttr= (T)metaProp.GetCustomAttributes(typeof(T), true).FirstOrDefault();
}
return custAttr;
}
检查两个地方有没有,这样就OK了