实体框架读取列,但阻止它被更新 [英] Entity Framework to read a column but prevent it being updated
问题描述
给定一个包含历史数据但不再填充的列的数据库表,Entity Framework中是否有一种方式来读取列,但是在使用相同的模型对象时会阻止它被更新?
Given a database table with a column that contains historic data but that is no longer populated, is there a way in Entity Framework to read the column but prevent it being updated when using the same model object?
例如我有一个对象
public class MyObject
{
public string CurrentDataColumnName { get; set; }
public string HistoricDataColumnName { get; set; }
}
从文档中我不相信我可以执行以下任一操作,因为这将停止EF读取数据以及持久化。
From the documentation I don’t believe I can do either of the following, because this will stop EF reading the data as well as persisting it.
(1)装饰 HistoricDataColumnName
属性具有以下属性
(1) Decorate the HistoricDataColumnName
property with the following attribute
[NotMapped]
(2)将 EntityTypeConfiguration
添加到 MyObject
Ignore(x => x.HistoricDataColumnName)
推荐答案
您可以将列标记为计算值,以防止Entity Framework更新/插入该列。
You can mark the column as computed to prevent Entity Framework from updating / inserting into that column.
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string HistoricDataColumnName { get; set; }
一个重要的数据库功能是具有计算
属性的能力。如果您将Code First类映射到
包含计算列的表,那么您不希望Entity Framework尝试
更新这些列。但是,在插入或更新数据之后,您需要EF从
数据库返回这些值。您可以使用
DatabaseGenerated注释来将类
中的属性与计算枚举一起标记。其他枚举是None和Identity。
An important database features is the ability to have computed properties. If you're mapping your Code First classes to tables that contain computed columns, you don't want Entity Framework to try to update those columns. But you do want EF to return those values from the database after you've inserted or updated data. You can use the DatabaseGenerated annotation to flag those properties in your class along with the Computed enum. Other enums are None and Identity.
这篇关于实体框架读取列,但阻止它被更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!