2

Possible Duplicate:
How to add validation to my POCO(template) classes

Hi all,

I'm using EF4 for Data Modeling and MVC for presentation. I have my entities defined and i want to use them in conjunction with Html.LabelFor(..) but that last method don't seem to work. Where can i define my dataannotations? Remember, all my entities are EF generated.

Thanks.

Community
  • 1
  • 1
TiagoDias
  • 1,785
  • 1
  • 16
  • 21

2 Answers2

3

Your best bet is to use the view model pattern and map the entities to view models. In summary, this involves mapping the data from your data/domain models to a flattened representation which is more compatible with your view, and does not mix your logic-concerns with your presentation concerns. Your DataAnnotations should go on your View Models.

Articles On View Models in ASP.NET MVC

These should help you understand how view models can improve your application and how to implement them.

I also suggest looking into AutoMapper, an excellent open source tool for automatically mapping your domain model (in this case entity framework classes) to your view model.

smartcaveman
  • 41,281
  • 29
  • 127
  • 212
  • If you do this you run the risk of needing to declare annotations multiple times for the same Entity. I know some people argue that the annotations should not be coupled to the data layer - but personally I disagree as the validation rules for an entity are unlikely to ever change as they are mapped to your database tables and I wouldn't think that it would be the case that you would dynamically update the TYPES of your database columns or the general functionality that a specific column provides to your app – Rob Mar 11 '11 at 23:43
2

Define your annotations like so:

[MetadataType(typeof(MetaDataBusiness))]
public partial class Business //Partial class for Entity
{
     //Don't need anything here for annotations to work
}

public class MetaDataBusiness
{
    [DisplayName("Business Id")]
    [Required(ErrorMessage = "Business Id is required")]
    [Range(0, Int32.MaxValue, ErrorMessage = "Business Id cannot be less than 0")]
    public int BusinessId { get; set; }
}
Rob
  • 10,004
  • 5
  • 61
  • 91
  • 1
    Don't do this. ViewModels make your Entity classes dependent on your UI layer when it should be the other way around. – John Farrell Mar 12 '11 at 14:26
  • @jfar - I suggest you read my comment above! I have my Entities declared in a DataTransfer project and I declare the Metadata in the same project - I mention nothing here about declaring this in the ViewModel! How a developer chooses to layout their project is not in question here. – Rob Mar 13 '11 at 02:17