Home > Software engineering >  Default Nullable Parameter in .net6 Entity Framework
Default Nullable Parameter in .net6 Entity Framework

Time:11-30

I'm trying to learn .NET Identity on a Udemy course. He uses .NET 5 but I'm trying it in .NET 6. He created 2 entities.

public class AppRole : IdentityRole<int>
{
    public DateTime CreatedTime { get; set; }
}
public class AppUser : IdentityUser<int>
{
    public string ImagePath { get; set; }

    public string Gender { get; set; }
}

When I tried these, in migrations ImagePath and Gender sections are nullable=false automatically.

ImagePath = table.Column<string>(type: "nvarchar(max)", **nullable: false**),
Gender = table.Column<string>(type: "nvarchar(max)",** nullable: false**),

**Is this because the difference of SDK's ? **

Should I use ? to make ImagePath and Gender nullable like below?

public string? ImagePath { get; set; }

public string? Gender { get; set; }

What is the proper way to get rid of this?

Should I remove the migrations and then create db again after add ? to properties.

CS8618 - Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable.

CodePudding user response:

In .NET 5 and earlier, all reference types are nullable and, in EF, you have to specify that the corresponding column is not null using an attribute or the fluent API in the DbContext. In .NET 6 and later, reference types are non-nullable by default and you specify that they are nullable by appending the ? to the type. In this context, string? in .NET 6 is equivalent to string in .NET 5. You should make that change and rebuild the database or apply a new migration.

  • Related