metadata与数据验证

metadata和数据验证都在 system.componentmodel.dataannotations命名空间下。 对于metadata,是因为我们ef databasefirst生成的model类每次 验证属性都会被清空,所以延伸出modelmetadata。

using System.ComponentModel.DataAnnotations; 
    [MetadataType(typeof(Product_MetaData))]
    namespace model
  {
  //放代码生成器的代码
    public partial class Product
    {
            public Guid ProductGuid { get; set; }
            public string ProductName { get; set; }
            public DateTime AddTime { get; set; }
  }
    using System.ComponentModel.DataAnnotations; 
namespace model
{//放扩展的数据验证等信息,构造函数等
        public class ProductMetaData
        {
            public Guid ProductGuid { get; set; }
            [Required(ErrorMessage = "产品名称不能为空")]
            public string ProductName { get; set; }
            public DateTime AddTime { get; set; }
         }
}
属性名称 说明
[Required] 必填字段
[MaxLength] 指定属性中允许的数组或字符串数据的最大长度
[MinLength] 指定属性中允许的数组或字符串数据的最小长度
[StringLength] 指定最小和最大字符长度
[Range] 指定数值范围数据验证相关的数据注解:
[Remote] 使用 jQuery 验证插件远程验证程序的特性
[FileExtension] 验证文件扩展名
[Compare] 比较两个属性的值
[RegularExpression] 使用正则表达式验证
[CustomValidation] 自定义验证方法
[DataType] 指定要与数据字段关联的附加类型的名称
[EmailAddress] 电子邮件地址(相当于[DataType(DataType.Email)])
[Phone] 电话(同上)
[CreditCard] 信用卡号码(同上)
[Url] 验证URL(同上)
[MemberShipPassword] 验证密码字段是否满足成员资格提供程序的当前密码要求数据映射相关的数据注解:
[Key] 主键字段
[Column] 数据库列属性映射
[NotMapped] 不要创建对应的字段
[Table] 指定类将映射到的数据库表
[ForeignKey] 表示关系中用作外键的属性
[DatabaseGenerated] 指定数据库生成属性值的方式(EF不追踪属性的变化)数据显示相关的数据注解:
[DisplayName] 指定本地化的字符串(习惯用语类)
[Display] 指定本地化的字符串(习惯用语属性)
[DisplayFormat] 设置数据字段的格式
[ReadOnly] 指定该特性所绑定到的属性是只读属性还是读/写属性
[EditAble] 指示数据字段是否可编辑
[HiddenInput] 指示是否应将属性值或字段值呈现为隐藏的 input 元素
[ScaffoldColumn] 指定类或数据列是否使用基架
[UIHint] 指定动态数据用来显示数据字段的模板其他
[DisplayColumn] 将所引用的表中显示的列指定为外键列
[Description] 可视化设计器在引用组件成员时可以显示指定的说明



1,数据验证相关的数据注解继承ValidationAttribute类,都有一个ErrorMessage属性用来显示错误提示。如:[Required(ErrorMessage=“此项不能为空”)]。
2、数据映射中Int类型和DateTime类型在数据库中默认不允许为NULL,如果需要设置为NULL,使用可空类型即可(使用Int?或者DateTime?)。

猜你喜欢

转载自blog.csdn.net/qq_37326058/article/details/83964778
今日推荐