【发布时间】:2018-09-11 14:21:29
【问题描述】:
在使用实体框架的项目中,假设我有一个实体,例如
[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 数据库上计算为 FirstName 和 LastName 的串联。
在项目开始时,整个表完全在本地加载。即通过DbContext.DbSet<MyTable>.Load()
在运行时我是
- 在代码中创建 this 的实例
- 设置此对象的名字和姓氏属性。
- 将此实例添加到
DbContext的DbSet - 致电
DbContext.SaveChanges()
现在,在调用SaveChanges() 之后,我期望实体的FullName 计算属性将填充计算值。但遗憾的是,这似乎没有发生?
如何从数据库中获取计算值到我的实体对象中?
【问题讨论】:
-
Maybe this helps。或者,您可以将
NotMapped属性 (System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute) 添加到您的FullName并将其设置器更改为get { return $"{this.LastName}, {this.FirstName}"; }
标签: c# sql-server entity-framework entity-framework-6 ef-code-first