必需的属性,但通过Code First可以实现Nullable,Entity Framework

时间:2016-08-06 02:00:23

标签: c# asp.net-mvc entity-framework ef-code-first ef-migrations

如何创建所需的属性(用于字段验证),但是对于数据库代码迁移是否为Nullable?

我有一个包含一千个条目的数据库表。最近需要添加一个必需的DateTime属性。

matrix(scan(text=df, sep="-", what ="", quiet=TRUE), ncol=4)
#      [,1]  [,2]  [,3]  [,4] 
#[1,] "Jan" "Jan" "Jul" "Jul"
#[2,] "01"  "01"  "06"  "06" 
#[3,] "Dec" "Jun" "Dec" "Dec"
#[4,] "31"  "30"  "31"  "31" 
#[5,] "00"  "12"  "09"  "09" 
#[6,] "00"  "00"  "00"  "00" 
#[7,] "24"  "18"  "19"  "19" 
#[8,] "00"  "00"  "00"  "00" 

如果我设置 [Required] [Display(Name = "Birth", Order = 10)] public DateTime? Birth { get; set; } 注释,则代码首次迁移将向列声明添加NOT NULL。但是,所有当前条目都没有"出生"数据。它将为NULL。

视图字段validatoin应该需要[Required]属性,但它可以在数据库中为空。这有可能吗?

我已经尝试添加"?" (可空)到财产和"虚拟"没有成功。

2 个答案:

答案 0 :(得分:7)

将您的模型用于数据库/实体通信。

为您的UI图层使用视图模型。在ViewModel中的属性上标记为必需,在模型上标记Nullable。根据需要在代码中执行转换。将所有与UI相关的属性修饰(如显示,验证/等)也移动到ViewModel。

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

答案 1 :(得分:2)

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

这样:

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

}

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

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

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

请注意,您需要

using System.Data.Entity.ModelConfiguration; 

在您的班级文件顶部。

然后在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”数据库字段应该可以为空。

我希望这会有所帮助。