我使用VS 2010 RTM并试图使用MetadataTypeAttribute简单类型执行一些基本的验证。当我把验证属性上的主类,一切正常。然而,当我把它放在元数据类,它似乎被忽略。我必须失去了一些小事,但我一直被困在这个有一段时间了。

我看了一下企业库验证模块作为一种解决方法,但它不支持单一性质的确认开箱。任何想法?

class Program
{
    static void Main(string[] args)
    {
        Stuff t = new Stuff();

        try
        {
            Validator.ValidateProperty(t.X, new ValidationContext(t, null, null) { MemberName = "X" });
            Console.WriteLine("Failed!");
        }
        catch (ValidationException)
        {
            Console.WriteLine("Succeeded!");
        }
    }
}

[MetadataType(typeof(StuffMetadata))]
public class Stuff
{
    //[Required]  //works here
    public string X { get; set; }
}

public class StuffMetadata
{
    [Required]  //no effect here
    public string X { get; set; }
}
有帮助吗?

解决方案

看来,验证不尊重MetadataTypeAttribute:

http://forums.silverlight.net/forums/p/149264 /377212.aspx

的关系必须人员显式登记:

 TypeDescriptor.AddProviderTransparent(
      new AssociatedMetadataTypeTypeDescriptionProvider(
          typeof(Stuff),
          typeof(StuffMetadata)), 
      typeof(Stuff)); 

此辅助类将注册在装配所有的元数据关系:

public static class MetadataTypesRegister
{
    static bool installed = false;
    static object installedLock = new object();

    public static void InstallForThisAssembly()
    {
        if (installed)
        {
            return;
        }

        lock (installedLock)
        {
            if (installed)
            {
                return;
            }

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
            {
                foreach (MetadataTypeAttribute attrib in type.GetCustomAttributes(typeof(MetadataTypeAttribute), true))
                {
                    TypeDescriptor.AddProviderTransparent(
                        new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type);
                }
            }

            installed = true;
        }
    }
}

其他提示

直供元数据类而不是主类的构造函数ValidationContext的实例,似乎为我工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top