Feature: Create Entities as nullable reference types
r-Larch opened this issue · comments
René Larch commented
Generate Entity Models with nullable reference type annotations.
Mark nullable columns as nullable reference types.
For Example:
nvarchar(100) NULL
->string?
nvarchar(100) NOT NULL
->string
Example Entity:
// 1. switch to nullable annotation context:
#nullable enable
// 2. disable some compiler warnings for non-nullable fields:
// (instead of doing this it would be possible to initialize non-nullable fields with `.. = null!` )
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public partial class BlogPost
{
public BlogPost()
{
#region Generated Constructor
#endregion
}
#region Generated Properties
public int BlogPostId { get; set; }
public string Title { get; set; }
public string? Text { get; set; }
#endregion
}
// 3. restore the warning
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public partial class BlogPostMap : IEntityTypeConfiguration<BlogPost>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<BlogPost> builder)
{
#region Generated Configure
// table
builder.ToTable("BlogPosts", "dbo");
// key
builder.HasKey(t => t.BlogPostId);
// properties
builder.Property(t => t.BlogPostId)
.IsRequired()
.HasColumnName("BlogPostId")
.HasColumnType("int")
.ValueGeneratedOnAdd();
builder.Property(t => t.Title)
.IsRequired()
.HasColumnName("Title")
.HasColumnType("nvarchar(100)")
.HasMaxLength(100);
builder.Property(t => t.Text)
.HasColumnName("Text")
.HasColumnType("nvarchar(4000)")
.HasMaxLength(4000);
#endregion
}
#region Generated Constants
public struct Table
{
public const string Schema = "dbo";
public const string Name = "BlogPosts";
}
public struct Columns
{
public const string BlogPostId = "BlogPostId";
public const string Title = "Title";
public const string Text = "Text";
}
#endregion
}
Paul Welter commented
This work was completed in version 4.5.
add the following to the configuration
project:
nullable: true