ASP.NET 表单验证/模型验证 - MetadataTypeAttribute

创建时间:
2015-10-23 11:48
最近更新:
2018-08-26 18:16

MSDN

MetadataTypeAttribute 类 - 指定要与数据模型类关联的元数据类

Syntax

[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false)]
public sealed class MetadataTypeAttribute : Attribute

Remarks

通过使用 MetadataTypeAttribute 特性,您可以将类与数据模型分部类关联。在此关联的类中,您可以提供数据模型中所没有的附加元数据信息。

Examples

using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer { }

public class CustomerMetaData
{
    // Apply RequiredAttribute
    [Required(ErrorMessage = "Title is required.")]
    public object Title;
}

Source Code of MetadataTypeAttribute from JetBrains dotPeek 1.0 at 2015-10-23

// Type: System.ComponentModel.DataAnnotations.MetadataTypeAttribute
// Assembly: System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ComponentModel.DataAnnotations.dll

using System;
using System.ComponentModel.DataAnnotations.Resources;
using System.Runtime;

namespace System.ComponentModel.DataAnnotations
{
  [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
  public sealed class MetadataTypeAttribute : Attribute
  {
    private Type _metadataClassType;

    public Type MetadataClassType
    {
      get
      {
        if (this._metadataClassType == (Type) null)
          throw new InvalidOperationException(DataAnnotationsResources.MetadataTypeAttribute_TypeCannotBeNull);
        else
          return this._metadataClassType;
      }
    }

    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    public MetadataTypeAttribute(Type metadataClassType)
    {
      this._metadataClassType = metadataClassType;
    }
  }
}

曾使用过的代码

namespace Mvc4AppBase.Edm
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    [MetadataType(typeof(RoleOfStaff_Metadata))]
    public partial class RoleOfStaff
    {
        private class RoleOfStaff_Metadata
        {
            //public RoleOfStaff()
            //{
            //  this.Staffs = new HashSet<Staff>();
            //}

            public byte RoleOfStaffId { get; set; }
            [Display(Name = "名字")]
            [StringLength(5)]
            [Required(ErrorMessage = "必须的")]
            public string Name { get; set; }
            public byte[] Purview { get; set; }
            public string Remark { get; set; }

            public virtual ICollection<Staff> Staffs { get; set; }
        }
    }
}

Resource

  1. 扩展 System.ComponentModel.DataAnnotations,解除对 MetadataType 的依赖