Adding validation to model with Database First model (EF 5)

时间秒杀一切 提交于 2019-12-23 15:35:06

问题


I know how to add validation errors to the model state. I know how to add the validation annotations to my model classes. The problem is that with Database first, I don't want to touch the generated code, because when I regenerate, I will lose my customization. I always try to customize in partials, but you can't add annotation to an existing property in a partial.

What is best practice here?


回答1:


You need to take advantage of MetadataTypeAttribute

Do something like this:

Create a new class file, keep it in the same namespace as your partial class. This new class will keep your validation rules even if you update your Model from Database. Modify the contents of your new class file like below, change to your specifications ,etc.

[MetadataTypeAttribute(typeof(YourCustomClassForValidation))]
public partial class Person
{
   // No need to put anything here because you already defined these properties
}

public class YourCustomClassForValidation
{
   [DisplayName("Full Name")]
    public string name { get; set; }
}



回答2:


You need to separate you EDMX file and entities:

  • EDMX file can be placed in Scaffolding project.
  • Entities can be placed in Data.Contracts project.

After updating EDMX model you need manually apply changes from newly generated entity on entity from Data.Contracts project.



来源:https://stackoverflow.com/questions/12866576/adding-validation-to-model-with-database-first-model-ef-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!