'Cannot insert the value NULL into column 'Description'. EF Core 5
I am using Entity Framework Core and I have this model class:
public class ConstraintRule
{
public int Id { get; set; }
public bool Enabled { get; set; }
public PlantFilterType PlantFilterType { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public string PowerplantIds { get; set; }
public string PowerplantTypes { get; set; }
public User User { get; set; }
public DateTime CreationTime { get; set; }
public string Description { get; set; }
public int Priority { get; set; }
}
This is the code in the context related to ConstraintRule model:
builder.Entity<ConstraintRule>(entity =>
{
entity.Property(e => e.Description).HasMaxLength(500);
entity.Property(e => e.PowerplantIds).HasMaxLength(2000);
entity.Property(e => e.PowerplantTypes).HasMaxLength(2000);
});
Description is a nullable string, this is the code generated by migration (also PowerplantIds and PowerplantTypes have the same problem):
migrationBuilder.AlterColumn<string>(
name: "Description",
table: "ConstraintRules",
type: "nvarchar(500)",
maxLength: 500,
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "nvarchar(500)",
oldMaxLength: 500,
oldNullable: true);
I get this error:
Cannot insert the value NULL into column 'Description'
Solution 1:[1]
The problem solved by changing string to string?:
public string? Description { get; set; }
The problem doesn't exist before updating to Dot NET core 5. This is a little confusing because string is a reference type and by default is nullable.
Edit: C# 8 introduced a new feature called nullable reference types (NRT), it's value is "annotations" by default (Non-nullable unless declared with ?). To disable this feature open csproj file and edit it:
<PropertyGroup>
<Nullable>disable</Nullable>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
