Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EF POCO classes as MVC 2 models (with data annotations)

I have a 4 layered web application programmed in C#... .Net 4.0:

  • UI Layer
  • Business Layer
  • Data access Layer
  • Entities layer

My data layer contains an edmx My entities layer contains my POCO objects (generated by a t4 script), and that layer is referenced in all other layers.

When creating an MVC form to create a new customer, for example.... I already have the customer class with fields for first name, last name, etc in my entities layer, but that auto-generated POCO class does not have data annotations for validation... I.E. [Required], etc. for when the form is submitted

My solution right now is to create new model classes that are pretty much the same as my poco classes but also have these additional validation annotations.

What I want to know is if theres an easy way to use certain POCO objects in the MVC model (in the UI layer) without having to almost rewrite the class... and also without modifying the t4 that generates these POCO classes (since I'm not up to speed on t4).

I saw this from another post on stackoverflow http://automapper.codeplex.com/ ... not sure if this will do it or is the best solution.

like image 497
Chris Klepeis Avatar asked Dec 17 '25 18:12

Chris Klepeis


1 Answers

If your POCO class is declared as such:

public class Person {
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}

then if you just change the T4 to make it a partial class, you can then define in a separate file:

[MetadataType(typeof(PersonMetadata))]
public partial class Person {

    internal class PersonMetadata {

        [Required]
        // insert other metadata here
        public string FirstName { get; set; }

        // and if you don't want metadata for lastname, you can leave it out
    }
}

Two extra points - the metadata class doesn't have to be nested in the partial you define, I think it's neater though. Also, the types don't have to match in the metadata class, so you could make them all object if you wanted to (and you might see some examples on the web with it like this)

like image 132
Jon Avatar answered Dec 20 '25 11:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!