将计算列的结果从数据库获取到实体中

Getting the result of a computed column from database into an entity

在使用 Entity Framework 的项目中,假设我有一个实体,例如

[Table("MyTable")]
public partial class MyTable
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [DatabaseGenerated( DatabaseGeneratedOption.Computed)]
    public string FullName { get; set; }
}

其中 FullName 是在 SQL Server 2012 数据库上计算的,作为 FirstNameLastName 的串联。

在项目开始时,整个 table 完全在本地加载。也就是说,通过 DbContext.DbSet<MyTable>.Load()

在运行的时候我是

  1. 正在代码中创建一个实例
  2. 正在设置此对象的名字和姓氏属性。
  3. 将此实例添加到 DbContext
  4. DbSet
  5. 呼叫DbContext.SaveChanges()

现在,在调用 SaveChanges() 之后,我期待实体的 FullName 计算 属性 填充计算值。但遗憾的是,这似乎并没有发生?

如何从数据库中获取计算值到我的实体对象中?

Where the FullName is computed on a SQL Server 2012 database as a concatenation of FirstName and LastName.

好吧,您没有将它们连接到 class 中的 FullName 属性,因为您使用的是 EF-Code First,因此您应该在 FullName 属性 中指定它=22=],像这样:

get { return string.Format("{0} {1}", FirstName, LastName); }

或者使用较新版本的 C#,您可以:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string FullName => $"{FirstName} {LastName}";

您不应在数据库和 class 中重复逻辑。您可能缺少的是对 EF Core 的指示,即该值是在数据库中生成的。在 OnModelCreating:

中使用 ValueGeneratedOnAddOrUpdate
modelBuilder.Entity<MyTable>()
    .Property(t => t.FullName)
    .ValueGeneratedOnAddOrUpdate();