13
votes

So I used this tutorial to generate my poco classes which I am to use throughout my aplication.. the problem is that Im not supposed to modify the generated cs files cause they get autoregenerated... How do I add attributes like [Required] and stuff like that?? please help

3

3 Answers

23
votes

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.

0
votes

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.

0
votes

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;
    }
}