开发者

Entity Framework - DataAnnotations

Using MVC3 and Entity Framework.

Am trying to get validation flowing from data model

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

Using example from: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx


I think the best option is not to mess with the class generated by EF. Instead define your own partial class:

[MetadataType(typeof(Person_Validation))]
public partial class Person
{
   //rest of class may be empty
}

You can do this in the same file as the Person_Validation class if you like.

It's not automatic, but it is safe (your changes won't get lost). This approach will work with any code generation framework (that uses partial classes), not just 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜