Entity Framework HasComputedColumnSql 方法returns 一个错误

Entity Framework HasComputedColumnSql method returns an error

我正在尝试通过向我的实体添加新的只读 属性 并使用 Context class 中的 HasComputedColumnSql 方法来向我的模型添加计算列。但是,这会导致带有消息

的 SqlException

'Invalid column name 'Date2'

实体class:

public partial class NetAssetsValue
{
     public string Key { get; set; }
     public string Date { get; set; }
     public DateTime? Date2 { get; } //readonly property for computed column
}

上下文 class:

public partial class EfficiencyContext : DbContext
{  
        public virtual DbSet<NetAssetsValue> Portfolio { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
                optionsBuilder.UseSqlServer("Server=someServer; Database=someDB; User Id=someID; Password=somePSD;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {    
            modelBuilder.Entity<NetAssetsValue>(entity =>
            {
                entity.HasNoKey();

                entity.ToTable("PortfFromSpecDep", "csv");

                entity.Property(e => e.Key)
                    .HasMaxLength(200)
                    .IsUnicode(false)
                    .HasColumnName("key");

                entity.Property(e => e.Date)
                    .HasMaxLength(200)
                    .IsUnicode(false)
                    .HasColumnName("date");
 
                // Error 'Invalid column name 'Date2' occurs here            
                entity.Property(e => e.Date2)
                    .HasComputedColumnSql("CONVERT(date, [date], 105)"); 
            }
        }
}

从数据库中检索数据的代码:

using EfficiencyContext db = new EfficiencyContext();

var query = db.Portfolio
              .Where(f => f.Date2 >= new DateTime(2021, 12, 30))
              .ToList();

foreach (NetAssetsValue nav in query)
{
    Console.WriteLine($"{nav.EntType} - {nav.FundName}");
}

Console.WriteLine(query.Count);
Console.ReadKey();

NotMappedAttributeIgnore 流利的方法 Api 也没有帮助。我正在使用 EF Core 5。我坚持这个。如果有任何建议,我将不胜感激。

注意:不幸的是,数据库中的日期列具有字符串 (varchar) 数据类型,我无法更改它。任何从字符串转换为 DateTime 的解决方案都不成功,因为日期列具有 dd.MM.yyyy 格式。这就是我决定使用计算列的原因。

尝试以下操作:

    public partial class NetAssetsValue
    {
        public string Key { get; set; }
        DateTime Date2 { get; set; } //readonly property for computed column
        public string Date { 
            get { return Date2.ToString("dd.MM.yyyy");}
            set {Date2 = DateTime.ParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture) ;} 
        }
    }