开发者

MVC3 Buddy Classes, ViewModels and Validation

开发者 https://www.devze.com 2023-03-18 09:28 出处:网络
I\'m currently working on my first MVC project which is nothing more than a glorified blog for my own learning purposes.I started out with a database-first approach as I had no idea code-first even ex

I'm currently working on my first MVC project which is nothing more than a glorified blog for my own learning purposes. I started out with a database-first approach as I had no idea code-first even existed at that point. That's left me with some confusion as to how I should be handling validation.

I have an Articles table in the database which has a corresponding Article class which has been generated for me by EF. I also have an ArticleViewModel class which has a matching property for each of the properties in Article. Whilst I have simple CRUD operati开发者_C百科ons working, they are currently using a strongly-typed Article model instead of ArticleViewModel and there is no data validation taking place.

After doing some research today to evaluate my options, I've found the following questions and this blog post. So it looks as though I can apply the MetadataType attribute to the EF generated classes and put my validation there, but I keep reading that buddy classes containing validation are bad practice. I have no idea why that is, but if that's the case, would that mean I should ignore buddy classes and be doing something like the following?

[MetadataType(typeof(ArticleViewModel))]
public partial class Article
{
    public Article(ArticleViewModel avm)
    {
        // Copy the properties from the ArticleViewModel into an Article.
    }
}

Then applying DataAnnotations to the ArticleViewModel as necessary and updating my controllers/views to use ArticleViewModel?

Thanks in advance for any input. :)


Yes, I've recently learned of this approach! and it is a good practice, as long as you don't mind the additional code involved. See Where do you put your validation in asp.net mvc 3? for more details and the accepted answer for a code example.

0

精彩评论

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