首页 > 解决方案 > 可选属性,但需要输入

问题描述

在我的特殊情况下,我正在从旧应用程序中导入数据。在新应用程序中,我有一个GradYear旧应用程序中不存在的模型属性 ( )。出于历史目的,我需要将数据从旧数据库导入到新数据库。但是,在新应用程序GradYear中是required.

使用 EF Core 和 Razor Pages,有没有办法GradYear在呈现的输入文本框级别设置为必需,但在 db 架构中是可选的?

标签: entity-frameworkasp.net-corerazor-pages

解决方案


I can think in this possible solution:

  1. Use a 2 different viewmodels, one for importing from legacy with non required field, other for internal new application use with required attribute, you just need to get sure in the non required viewmodel that you assign a default value when mapping to the DBContext entity.

Another way (not tested) is decorate your property as required but override OnModelCreating like this :

public class YourAppContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      ...
      modelBuilder.Entity<YourDbContextEntity>.Property(p => p.GradYear).IsOptional();
      ...
   }

}

推荐阅读