Saqlain Mushtaq
Saqlain Mushtaq

Reputation: 193

String is not nullable by default in Entity Framework Core 6.0

I was creating a database table in Entity Framework Core 6.0. I was using code first approach in my project.

There was a string type property in TestModel named Address.

enter image description here

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace TestProjectForCore6.Models
{
   public class TestModel
   {
       [Key]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public int Id { get; set; }
       public string Address { get; set; }
   }
}

When I add migration for this model, it creates a nullable false column in migration builder:

enter image description here

In Entity Framework Core 5.0, we don't need to add explicitly define string property as nullable.

Upvotes: 7

Views: 13856

Answers (4)

A30
A30

Reputation: 21

make it nullable in your Context file by this code:

protected override void OnModelCreating (ModelBuilder modelBuilder)
{
    modelBuilder.Entity<TestModel>().Property(x =>x.Address).HasDefaultValue(null);
}

Upvotes: 1

Tony Thomas
Tony Thomas

Reputation: 436

I could manage this by adding symbol:

#nullable disable

at the very top of the entity class in addition to the same symbol at the top of the DataContext class

Upvotes: 1

Mateech
Mateech

Reputation: 1064

You can asign your property as nullable and after migration you will see the changes

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace TestProjectForCore6.Models
{
   public class TestModel
   {
       [Key]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public int Id { get; set; }
       public string? Address { get; set; }
       //add this   ↑
   }
}

Upvotes: 5

Just need to remove this line "enable" on .csproj file

enter image description here

Upvotes: 12

Related Questions