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; }
}
}