I have a bunch of Entity classes generated automatically from from a database connection. I 'd like to add data annotations automatically, for example if a column is of type varchar(100), then i'd like to have the data annotation [StringLength(100)]
, or if it is not a nullable field, I'd like to have the [Required]
annotation. Is this possible?
The only question I found about this is almost 10 years old and the answer at the time is no longer working.
Thanks in advance for any help.
With some more research and some trial and error I managed to do it. Basically it involves editing the T4 template generated by Entity Framework.
After you add the ADO.NET Entity Data Model
> EF Designer from data...
, you get an EDMX file, and if you expand it on Visual Studio there's a .tt file with the same name as the .edmx file.
On that file, I added under <#=codeStringGenerator.UsingDirectives(inHeader: false)#>
the using
statement for data annotations:
using System.ComponentModel.DataAnnotations;
Then, a few lines below, after the simpleProperties
declaration, in the foreach
I added the following:
foreach (var edmProperty in simpleProperties) // <-- Original foreach statement
{
if(edmProperty.Nullable == false)
{
#> [Required]
<#
}
if(edmProperty.MaxLength != null)
{
#> [StringLength(<#=edmProperty.MaxLength#>)]
<#
}
//Rest of the auto-generated code...
Saving this file will update the auto-generated .cs files accordingly:
namespace MyNamespace
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class MyModel
{
[Required]
public int Id { get; set; }
[Required]
[StringLength(20)]
public string MyField { get; set; }
}
}