实体框架中的详细对象状态?

时间:2012-06-26 20:20:18

标签: entity-framework entity-framework-4

如何仅为实体的属性获取状态?

让我们说我有一个产品类的对象,只有它的价格值已经改变所以我现在想:

  1. ProductName Unchanged
  2. ProductPrice Modified
  3. 很容易知道对象已被更改但我想知道已更改的确切属性。

    我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

使用ObjectStateEntry像这样调用GetModifiedProperties方法(这里有比你需要的更多样本,但是看看下面代码中的GetModifiedProperties):

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);
}

答案 1 :(得分:1)

浏览一下这个互联网,我发现this article说明了你想要做什么。