【问题标题】:Detailed state of object in Entity Framework?实体框架中对象的详细状态?
【发布时间】:2012-06-26 20:20:17
【问题描述】:

我怎样才能只为实体的属性而不是实体获取状态?

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

  1. 产品名称不变
  2. ProductPrice 修改

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

我该怎么做?

【问题讨论】:

  • 看起来像是this question的骗子
  • 不,这不是同一个问题!!!
  • 看看最底部答案中的链接

标签: entity-framework entity-framework-4


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    环顾互联网,我发现this article 正是您想要做的事情。

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 2012-10-28
      • 2011-11-26
      相关资源
      最近更新 更多