实体框架 - DataAnnotations [英] Entity Framework - DataAnnotations
问题描述
使用MVC3和Entity Framework。
Using MVC3 and Entity Framework.
想获得验证从数据模型流动
Am trying to get validation flowing from data model
问:在实体框架保存,我怎么能自动地把在[MetadataType标签下面我哥们类
Question: On an entity framework save, how can I automatically put in the [MetadataType tag below for my buddy class?
[EdmEntityTypeAttribute(NamespaceName="ModelValidationTestModel", Name="Person")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
[MetadataType(typeof(Person_Validation))] // I want EF to put this line in automatically
public partial class Person : EntityObject
...
[Bind(Exclude="PersonID")]
public class Person_Validation
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Email { get; set; }
}
使用例如来自:的http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
推荐答案
数据注释/属性在编译时烤,你不能动态地添加。我建议你避免将/让你的EF模型/从意见。你应该使用的是专门针对给定视图的需求类视图模型。正是这些视图模型将处理会处理视图特定的验证这样的要求,格式,...)。然后,您可以使用 AutoMapper 让您的视图模型和EF模型之间控制器的地图。
Data Annotations/attributes are baked at compile time and you cannot add them dynamically. I would recommend you to avoid passing/getting your EF models to/from the views. You should be using view models which are classes specifically tailored to the needs of a given view. It is those view models that will handle the would handle view specific validations such required, format, ...). You could then use AutoMapper to have your controller map between your view models and the EF models.
这篇关于实体框架 - DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!