13

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 Answers 3

23

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.

9
  • 3
    If you downvote it would be nice to let me know why? If my answer is incorrect I will modify or delete it ... Feb 26, 2011 at 17:13
  • 1
    Advocating metadata buddy classes is advocating a bad practice. Feb 26, 2011 at 17:17
  • 4
    @jfar: Ok. Did you read last paragraph? :) I'm always trying to answer the question as well as provide the best practice if I don't agree with solution. Feb 26, 2011 at 17:22
  • 2
    @jfar: You should go and downvote MS as well because EF Code First introduces DataAnnotations on POCO entities as common scenario: blogs.msdn.com/b/adonet/archive/2010/12/15/… Just kidding. I understand your concerns. Feb 26, 2011 at 17:54
  • 2
    @jfar, why you so hate those DataAnnotation attributes? Sure, there is no place for them in the Entity classes but they work pretty well with ViewModels.
    – Vasiliy R
    Feb 26, 2011 at 18:52
0

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.

2
  • Those attributes are generated by EF? or one must to find a way to add them to the POCO classes?
    – polkduran
    Jun 19, 2013 at 15:58
  • If the facets are on the model, EF will add the appropriate attributes when it generates the POCOs. So to coerce a particular attribute, you need to know how to tweak the model. Jul 31, 2013 at 1:31
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.