c# - Entity Framework 读取列但阻止更新

标签 c# entity-framework

给定一个包含历史数据但不再填充的列的数据库表, Entity Framework 中是否有一种方法可以读取该列,但在使用相同的模型对象时阻止它被更新?

比如我有一个对象

public class MyObject
{
    public string CurrentDataColumnName { get; set; }
    public string HistoricDataColumnName { get; set; }
}

根据文档,我认为我无法执行以下任一操作,因为这将停止 EF 读取数据并保留数据。

(1) 用以下属性修饰 HistoricDataColumnName 属性

[NotMapped]

(2) 将以下内容添加到我的EntityTypeConfiguration for MyObject

Ignore(x => x.HistoricDataColumnName)

最佳答案

您可以将列标记为已计算,以防止 Entity Framework 更新/插入该列。

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

DatabaseGenerated

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.

关于c# - Entity Framework 读取列但阻止更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30777503/

相关文章:

c# - 使用 Eval 从通用列表创建逗号分隔的字符串

c# - 如何从在 UWP 应用程序中运行 IoT Core 的 Raspberry Pi 访问网络共享

c# - 无法在 .NET 4 的 IIS 中看到 .NET 用户

c# - 当我需要多个相同类型的关系时 Entity Framework 出现问题

c# - 需要帮助理解代码

c# - 为只读字段调用不纯方法

c# - Entity Framework Code First MySql 复数表

entity-framework - 这是 Entity Framework 的预期行为还是错误?

entity-framework - 在 Entity Framework 中没有数据库调用的情况下从 EntityKey 构造 EntityObject

c# - 如何将 Entity Framework 查询写成 **like 'lap%' **