如何在EF中获得实体更改增量?

Kum*_*mar 9 .net c# entity-framework sql-server-ce

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

EF中是否有任何支持来获取列表或构建通用组件?

vit*_*ore 7

根据上下文的类型和生成的实体,您可以通过多种不同的方式执行此操作.如果从Entity或POCO继承的对象可以ObjectStateManager 在自我跟踪实体的情况下使用,则可以使用实体本身的Tracker.

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

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

 var changed = ctx.ObjectStateManager.GetObjectStateEntries().Where(e=>e.State != EntityState.Unchanged);
Run Code Online (Sandbox Code Playgroud)

编辑(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);
}
Run Code Online (Sandbox Code Playgroud)