gpt4 book ai didi

c# - 如何在 EF 中获取实体更改增量?

转载 作者:太空狗 更新时间:2023-10-29 17:49:49 25 4
gpt4 key购买 nike

我只需要获取已更改字段的列表,数据存储是 ssce,因此没有可用的触发器

EF 是否支持获取列表或构建通用组件?

最佳答案

根据上下文的类型和生成的实体,您可以通过几种不同的方式来完成。对于从 Entity 或 POCO 继承的对象,您可以使用 ObjectStateManager如果是 self 跟踪实体,您可以使用实体本身的跟踪器。

请提供更多关于您如何生成上下文以及如何进行更改的详细信息

编辑(2):您可以像这样查询 ObjectStateManager 更改的条目:

 var changed = ctx.ObjectStateManager.GetObjectStateEntries().Where(e=>e.State != EntityState.Unchanged);

编辑(1):

以下例子来自MSDN演示如何查询更改:

int orderId = 43680;

using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
var order = (from o in context.SalesOrderHeaders
where o.SalesOrderID == orderId
select o).First();

// Get ObjectStateEntry from EntityKey.
ObjectStateEntry stateEntry =
context.ObjectStateManager
.GetObjectStateEntry(((IEntityWithKey)order).EntityKey);

//Get the current value of SalesOrderHeader.PurchaseOrderNumber.
CurrentValueRecord rec1 = stateEntry.CurrentValues;
string oldPurchaseOrderNumber =
(string)rec1.GetValue(rec1.GetOrdinal("PurchaseOrderNumber"));

//Change the value.
order.PurchaseOrderNumber = "12345";
string newPurchaseOrderNumber =
(string)rec1.GetValue(rec1.GetOrdinal("PurchaseOrderNumber"));

// Get the modified properties.
IEnumerable<string> modifiedFields = stateEntry.GetModifiedProperties();
foreach (string s in modifiedFields)
Console.WriteLine("Modified field name: {0}\n Old Value: {1}\n New Value: {2}",
s, oldPurchaseOrderNumber, newPurchaseOrderNumber);

// Get the Entity that is associated with this ObjectStateEntry.
SalesOrderHeader associatedEnity = (SalesOrderHeader)stateEntry.Entity;
Console.WriteLine("Associated Enity's ID: {0}", associatedEnity.SalesOrderID);
}

关于c# - 如何在 EF 中获取实体更改增量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com