2012-06-26 52 views
2

如何才能獲得僅針對非實體的實體的財產狀態?實體框架中對象的詳細狀態?

讓我們說我有一個從產品檔次,只有它的價格值的對象已經改變,所以我想現在是:

  1. 產品名稱不變
  2. ProductPrice修改

這很容易要知道該對象已被更改,但我想知道已更改的確切屬性。

我該怎麼做?

+0

好像的[這個問題]愚弄的人( http://stackoverflow.com/questions/2714857/how-to-tell-if-any-entities-in-context-are-dirty-with-net-entity-framework-4-0) – bluevector

+0

不是它的不一樣題!!! –

+0

看看最底部答案中的鏈接 – bluevector

回答

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