I have the following class generated by entity framework:
public partial class ItemRequest
{
public int RequestId { get; set; }
//...
I would like to make this a required field
[Required]
public int RequestId { get;set; }
However, because this is generated code this will get wiped out. I can't imagine a way to create a partial class because the property is defined by the generated partial class. How can I define the constraint in a safe way?
As MUG4N answered you can use partial classes but will be better use interfaces instead. In this case you will have compilation errors if EF model doesn't correspond to validation model. So you can modify your EF models without fear that validation rules are outdated.
P.S. If you are using project type which is differ from ASP.NET MVC (when you perform manual data validation) don't forget to register your validators
I am not sure how to do what you are asking for but there is a way around it. Dynamic data validation by overriding the GetValidators of your custom DataAnnotationsModelValidatorProvider. In it you can read the rules for validating each field (from a database, config file, etc.) and add validators as need be. It has the added values that your validation is no longer tightly coupled to the model and can be changed without need to even restart the site. Of course it might be overkill for your case, but it was ideal for ours!
I found a solution like MUG4N's answer, but instead, nesting the
MetaData
class within the entity class, thereby reducing the number of classes in your public namespace list, and eliminating the need to have a unique name for each metadata class.This is sort of extension to @dimonser answer if you regenerate your db model you will have to manually re-add interfaces on those classes.
If you have stomach for it you can also modify your
.tt
templates:Here's example of auto-generating interfaces on some classes, this is fragment from
.tt
just replaceEntityClassOpening
method in yours with following (and obviouslyvar stringsToMatch
with your entity names and interfaces).No normal person should do this to himself though, it has been proven in Bible that one goes to Hell for this.
Modify the T4 template adding required annotations, this file is usually named MODELNAME.tt
find where the T4 is creating the class and methods to know where to put these.
You will also need to add the namespaces;
Rebuild your classes by saving your model, all your methods should be annotated.
The generated class
ItemRequest
will always be apartial
class. This allows you to write a second partial class which is marked with the necessary data annotations. In your case the partial classItemRequest
would look like this: