问题
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