2014-09-04 34 views
0

我有一個審計方法,記錄對我的數據庫的更改。MVC 5獲取DbEntry的DisplayFormatAttribute

簡化這樣

private List<Case_History> GetRecords(DbEntityEntry dbEntry, ApplicationUser user, int actionID) 
{ 
    List<Case_History> result = new List<Case_History>(); 

    DateTime changeTime = DateTime.Now; 

    // Finds the table 
    TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute; 

    // Finds the table name 
    string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().BaseType.Name; 

    // Finds primary key 
    string keyName = dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name; 

else if (dbEntry.State == EntityState.Modified) 
{ 
    List<string> values = new List<string>(); 

    foreach (string propertyName in dbEntry.OriginalValues.PropertyNames) 
    { 
     if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName)) && propertyName != "Modified_date") 
     { 
      //DEBUGGING VARIABLE 
      var originalValue = dbEntry.OriginalValues.GetValue<object>(propertyName); 
      //DEBUGGING VARIABLE 
      var newValue = dbEntry.CurrentValues.GetValue<object>(propertyName); 

      //Here is the part where i want to get the column display name 
      // This code is not working 
      PropertyInfo prop = typeof(this).GetProperty(propertyName); 
      var att = (DisplayAttribute)prop.GetCustomAttributes(typeof(DisplayAttribute); 
      if (att != null) 
      { 
       //found Display name 
      } 

      //If the record is different, record the change 
      if (dbEntry.OriginalValues.GetValue<object>(propertyName) != null && dbEntry.CurrentValues.GetValue<object>(propertyName) != null) 
      { 
        values.Add(propertyName + ": " + dbEntry.OriginalValues.GetValue<object>(propertyName).ToString() + " -> " + dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()); 

      } 
     } 
    } 
} 

方法長相(升技)我已發現在局部變量該變量在該領域的元數據propterties調試會話。但只限於「這個」變量。這對每個不同的DBentries都必須是動態的。

+0

爲什麼不更換的typeof實體屬性(這)到dbEntry.Entity.GetType()? – 2014-09-04 12:48:26

+0

啊,哦,哇。是的,這是很容易:)非常感謝。 – stibay 2014-09-04 12:56:33

回答

1

只需更換

PropertyInfo prop = typeof(this).GetProperty(propertyName); 

通過

PropertyInfo prop = dbEntry.Entity.GetType().GetProperty(propertyName); 

事實上, 「本」 是當前的類,它不包含從要登錄