2

如何仅获取实体的属性而不是实体的状态?

假设我有一个产品类的对象,只有它的价格值发生了变化,所以我现在想要:

  1. 产品名称不变
  2. 产品价格修改

很容易知道对象已更改,但我想知道已更改的确切属性。

我怎么能这样做?

4

2 回答 2

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);
}
于 2012-06-27T01:39:13.280 回答
1

环顾互联网,我发现这篇文章正是你想要做的。

于 2012-06-26T20:56:53.347 回答