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?

1
  • 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. Commented Oct 12, 2012 at 20:58

2 Answers 2

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.