必需 属性 但可空,Entity Framework 通过代码优先

Required property but Nullable, Entity Framework through Code First

如何使 属性 成为必需项(用于字段验证)但对于数据库代码迁移可为 Nullable?

我确实有一个包含一千个条目的数据库 table。最近需要添加所需的 DateTime 属性。

    [Required]
    [Display(Name = "Birth", Order = 10)]
    public DateTime? Birth { get; set; } 

如果我设置 [Required] 注释,代码优先迁移会将 NOT NULL 添加到列声明中。但是,所有当前条目都没有 "Birth" 数据。它将为 NULL。

Birth 属性 应该是视图字段验证所必需的,但它可以在数据库中为空。这有可能吗?

我已经试过添加“?” (可为空)到 属性 和 "virtual" 没有成功。

使用您的模型进行 DB/Entity 交流。

为您的 UI 层使用视图模型。在 ViewModel 的 属性 上标记 Required,在模型上标记 Nullable。根据需要在您的代码中执行转换。将所有 UI 相关的属性装饰(如 Display,validation/etc)也移动到 ViewModel。

可以通过 NuGet 包管理器使用 AutoMapper plugin, available 自动执行转换。

一种快速的方法是覆盖数据库上下文的 OnModelCreating() 方法。

这样:

public class AppContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      // ...
      modelBuilder.Entity<YourModelEntity>.Property(p => p.Birth).IsOptional();
   }

}

或另一种正确的方法是,您可以为模型创建通用 EntityTypeConfiguration 类型的扩展 class,然后将此特定配置添加到 OnModelCreating() 方法中的 DBModelBuilder 中:

public class YourModelTypeConfiguration : EntityTypeConfiguration<YourModelType>
{
    public YourModelTypeConfiguration()
    {
        // ... some other configurations ;

        Property(p => p.Birth).IsOptional();
    }
}

请注意,您需要

using System.Data.Entity.ModelConfiguration; 

在您的 class 文件的顶部。

然后在 OnModelCreating() 方法中添加:

    public class AppContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      // quick and dirty solution
      // modelBuilder.Entity<YourModelEntity>.Property(p => p.Birth).IsOptional()

      // cleaner solution
      modelBuilder.Configurations.Add(new YourModelTypeConfiguration());
   }

}

这样您就可以将您的特定配置分开,而不是将所有内容混合在一起。

应用代码首次迁移时,"Birth" 数据库字段应该可以为空。

希望对您有所帮助。