开发者

Entity Framework and MVC [duplicate]

This question already has answers here: Closed 11 years ago.

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 data开发者_开发技巧annotations? Remember, all my entities are EF generated.

Thanks.


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.

  • http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
  • http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx
  • http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

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.


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜