4

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?

sheamus
  • 3,001
  • 4
  • 31
  • 54
  • I should add that what a I currently do is create a ViewModel, but that feels a little redundant, espcially because I am already creating a veiw model in Knockout JS. – sheamus Oct 12 '12 at 20:58

2 Answers2

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; }
}
pb2q
  • 58,613
  • 19
  • 146
  • 147
precator
  • 11
  • 1
  • This solved an issue for me where I had no model file to add annotations to. Someone created an older .Net Web App and created an edmx type system, which I've never used before, only code first. So I had no idea how to add annotations to the properties. Creating the metadata class allowed me to add annotations to the properties. – Daniel Jackson Dec 11 '18 at 17:15
0

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.

Vlad Omelyanchuk
  • 3,021
  • 7
  • 29
  • 35