如何获得实体的变化三角洲EF?如何获得、实体、EF

由网友(我是太阳何须温暖)分享简介:我需要不仅改变字段列表,数据存储是SSCE所以没有可用的触发器包括I need to get the list of changed fields only, the datastore is ssce so no triggers are available是否有EF任何支持来获得一个列表,或建立一个通用的组件?...

我需要不仅改变字段列表,数据存储是SSCE所以没有可用的触发器包括

I need to get the list of changed fields only, the datastore is ssce so no triggers are available

是否有EF任何支持来获得一个列表,或建立一个通用的组件?

Is there any support in EF to get a list or to build a generic component ?

推荐答案

根据上下文的类型和产生的实体可以用几种不同的方式做到这一点。 如果对象从实体或POCO可以使用 ObjectStateManager 如果自跟踪实体的,你可以使用跟踪从实体本身。

Depending on the type of context and generated entities you can do it in several different ways. In case of objects inherited from Entity or POCO you can use ObjectStateManager in case of Self-Tracking entities you can use Tracker from entity itself.

请提供您如何产生的上下文的方式的详细信息,以及如何修改

please provide more details on the way how you generated context and how you make changes

EDITED(2): 您可以查询 ObjectStateManager 的修改条目只是这样的:

EDITED(2): you can query ObjectStateManager for changed entries simply like this:

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

编辑(1):

EDITED(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);
}
阅读全文

相关推荐

最新文章