How to add validation to my POCO(template) classes

泄露秘密 提交于 2019-11-26 14:38:17

You can't add it directly (unless you modify T4 template to create them for you) but you can try to use trick introduced in ASP.NET dynamic data. All POCO classes are defined as partial. So lets define your partial part:

using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(MyClassMetadata))]
public partial class MyClass
{
  private class MyClassMetadata
  {
     [Required]
     public object Id;

     [Required]
     [StringLength(100)]
     public object Name;
  }
}

Metadata class is special type to hold only metadata - it is never used. Name of fields must be same as corresponding fields in real class (field types doesn't matter so you can use object).

Anyway in ASP.NET MVC you should use specialized View model for each view and pass data you need so the validation attributes will be placed in view model class.

The attributes on the generated POCOs are derived from the facets on the entities in the model. e.g. for [Required] make sure the field is "not null" and for [StringLength(n)] make sure the datatype is nvarchar(n) via the MaxLength facet.

Further expanding on the answer. By using Microsoft Patterns & Practices Enterprise Library 5 Validation Block, you can open up a wealth of validation possibilities beyond those available through normal data annotations.

using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

[HasSelfValidation]
public partial class Category : ICategory
{
    [SelfValidation]
    public void Validate(ValidationResults validationResults)
    {
        if (this.Title === "Credo")
        {
            validationResults.AddResult(
                new ValidationResult(
                    "Category title cannot be a veiled reference to a former cool 2000AD character.",
                    this,
                    null,
                    null,
                    null));
        }

        validationResults.AddAllResults(
            ValidationFactory
            .CreateValidator<ICategory>()
            .Validate(this));
    }
}

using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

public interface ICategory
{
    int Id
    {
        get; 
        set;
    }

    [Required]
    [StringLengthValidator(1, 50, MessageTemplate = "Category title should be a maximum of 50 characters in length.")]
    string Title
    {
        get; 
        set;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!