2
votes

I was using EF 4.x database-first approach. I have the edmx file and it generated the C# class that derived from EntityObject. I have an ASP.NET MVC 4 application that uses the generated class as model. The client validation that validates the required fields worked fine.

Now I moved to EF 5 and used the DbContext generator, it generates the POCO C# class. I found that the required field validation no longer works in EF 5.

I think the problem is that in EF 4.x EntityObject generator, the generated class has [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] attribute. However in the EF 5.x POCO class, no data annotation attributes are generated. So the required field information is lost.

So my questions are:

  1. Why does the EF 5.x DbContext generator not generate [Required] annotations from the edmx file?
  2. Where is the right place to put these data annotations? Should I modify the .tt file to generate the [Required] attribute? Or manually write a [MetadataType] partial class and define data annotation attributes in a separate class?
2

2 Answers

0
votes

1) I don't know why. I just know that Db-first approach doesn't add any data annotations to properties.

2) Indeed creating a separate partial class! Here is an example. Because EF will overwrite and regenerate all POCO classes every time you update your model, any changes (also data annotations) to those classes will be lost...

0
votes

Perhaps you can find this link useful. EF Validation Simply add Metadata class with the required validation:

[MetadataType(typeof(UserMetadata))
public partial class User
{
  ...
}
public class UserMetadata
{
    [UserValidate("State")]
    public string State; 
   // etc.
}

hope this can help