开发者

ASP.NET MVC POCO classes and validation

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 th开发者_StackOverflow中文版em 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)?


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.


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(); }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜