繁体   English   中英

String 在 Entity Framework Core 6.0 中默认不可为空

[英]String is not nullable by default in Entity Framework Core 6.0

我在 Entity Framework Core 6.0 中创建了一个数据库表。 我在我的项目中使用代码优先方法。

TestModel中有一个名为Address的字符串类型属性。

在此处输入图像描述

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; }
   }
}

当我为此 model 添加迁移时,它会在迁移生成器中创建一个可为nullable false列:

在此处输入图像描述

在 Entity Framework Core 5.0 中,我们不需要添加显式定义字符串属性为可为空。

只需要删除这一行“启用”on.csproj 文件

在此处输入图像描述

您可以将您的属性指定为可为空,迁移后您将看到更改

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   ↑
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM