Home > Enterprise >  EF Core Scaffolding missing [Required] for Certain Types
EF Core Scaffolding missing [Required] for Certain Types

Time:06-21

VS 2019 trying to EF Core scaffolding tables from SQL Server 2012 (v11.07), notice it cannot generate [Required] annotation for certain column types: datetime, datetime2, int, for example

create table dbo.test2 
(
    d datetime not null, 
    d2 datetime2 not null,
    i int not null, 
    txt varchar(100) not null 
)
Scaffold-DbContext "..." 
    -Provider Microsoft.EntityFrameworkCore.SqlServer 
    -ContextDir Data -OutputDir "Data/Models" 
    -DataAnnotations -UseDatabaseNames -Tables "test2"

Result:

{
    [Keyless]
    [Table("test2", Schema = "dbo")]
    public partial class test2
    {
        [Column(TypeName = "datetime")]
        public DateTime d { get; set; }
        public DateTime d2 { get; set; }
        public int i { get; set; }
        [Required]
        [StringLength(100)]
        public string txt { get; set; }
    }
}

Some project properties:

<TargetFramework>netcoreapp3.1</TargetFramework>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.10">

CodePudding user response:

Since your int and DateTime properties are not marked as nullable (with ? sign - e.g. int?) - they are considered as Required by default. It is applied only to value types (structs as DateTime or primitives as int). You can read more here

  • Related