1

I've got three projects/libraries.

SiteService (WCF Service)
SiteModel (POCO objects)
SiteMVC (Web Application)

In my SiteModel library i've only got POCO objects. These objects are generated by an t4 template, so I prefer not to change anything. The SiteService uses these POCO objects and serializes them (thats the reason for using POCO objects instead of the generated classes from the EF designer)

In the WebApplication I want to use validation on these POCO objects. I want to keep my Model library as clean as possible and not use DataAnnotations on them because the rules may vary in the different applications.

What is the best way for validation in ASP.NET MVC2? Is it possible to use DataAnnotations (buddy class)?

2 Answers 2

3

If your T4 template generates partial classes, then you're in luck.

You can create a separate partial definition and decorate it with MetadataType:

// T4 Generated Code
public partial class Item
{
    public int Id { get; set; }
    public string Name { get; set; }        
}

// Your partial in a separate file
[MetadataType(typeof(ItemValidation))]
public partial class Item
{
}

// Any DataAnnotations go here
public partial class ItemValidation
{
    [Required(ErrorMessage = "You need to have a Name!")]
    public string Name { get; set; }
}

Otherwise, your only other option would be to create ViewModels with DataAnnotations in the Web Project and then map between your Models (clean POCO objects) and your ViewModels.

Sign up to request clarification or add additional context in comments.

3 Comments

+1: clever (but I guess you missed the second public partial class Item declaration).
@rsenna - I was too worried about getting the rest of it typed. Haha. Fixed.
How does this works with the different namespaces. I got problems with ambiguous class names..
0

FYI. While the partial class works. If you are using RIA or WCF and want the property to show up you need to add the [DataMember] attribute.

public partial class Employee
{       
    [DataMember]
    public string ComposedName
    {
        get
        {
            return String.Format("{0}, {1}", this.LastName, this.FirstName);
        }
        set
        { throw new NotImplementedException(); }
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.