2014-01-08 88 views
2

我想創建一個保存點使用實體框架的任何更改的審計日誌。到目前爲止,我有這還算運作良好,使用下面的代碼保存到每個字段進行的所有更改:如何從DBEntityEntry獲取外鍵值?

foreach (string propertyName in dbEntry.OriginalValues.PropertyNames) 
{ 
    // For updates, we only want to capture the columns that actually changed 
    if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName))) 
    { 
     result.Add(new AuditLog() 
     { 
      UserID = UserId, 
      EventDateUTC = changeTime, 
      EventType = "M", // Modified 
      TableName = tableName, 
      RecordID = primaryKey.ToString(), 
      ColumnName = propertyName, 
      OriginalValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(), 
      NewValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString() 
     }); 
    } 
} 

我現在面臨的問題是如何獲得值屬於該對象的任何外鍵。例如:我有一個車輛對象與一系列查找表(如變速箱,模型等)有關係。如果這些值更改,審計表將存儲更改的ID,但我想存儲實際值。

有沒有辦法在這種情況下獲得外鍵值?

回答

1

Alrighty ...這是一個古老的問題,但我已經花了最後一個工作,因爲我有完全相同的要求。也許還有一個更簡單的方法,但這裏是我使用的代碼:

你的原代碼,稍加修改,我的目的(的recordId始終是一個int),並調用新的方法來計算新的價值

foreach (string propertyName in dbEntry.OriginalValues.PropertyNames) 
      { 
       // For updates, we only want to capture the columns that actually changed 
       if (!Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName))) 
       { 
        var newVal = getNewValueAsString(dbEntry, tableName, propertyName); 

        result.Add(new AuditLog 
           { 
            UserID = currentUser.ID, 
            Timestamp = changeTime, 
            EventType = EventType.Modified, 
            TableName = tableName, 
            RecordID = dbEntry.OriginalValues.GetValue<int>(keyName), 
            ColumnName = propertyName, 
            OriginalValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(), 
            NewValue = newVal 
           } 
         ); 
       } 
      } 

稱爲「IsName」

​​

標誌着「名」與IsName屬性(注意代碼將默認爲一個名爲「名稱」屬性,如果它沒有找到一個外鍵模型的屬性的新屬性)

[Required] 
[IsName] 
public string Name { get; set; } 

而繁重的代碼

private string getNewValueAsString(DbEntityEntry dbEntry, string tableName, string propertyName) 
    { 
     var fkVal = getForeignKeyValue(tableName, propertyName, dbEntry.CurrentValues.GetValue<object>(propertyName)); 
     return fkVal != null ? fkVal.ToString() 
          : (dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null 
           : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()); 
    } 

    private object getForeignKeyValue(string tableName, string propertyName, object foreignKeyID) 
    { 
     // if this property is part of a foreign key, we need to instead look that up and store the value of the 
     // foreign key 

     // first get all the foreign keys in the system 
     var workspace = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace; 
     var items = workspace.GetItems<AssociationType>(DataSpace.CSpace); 
     if (items == null) return null; 
     var fk = items.Where(a => a.IsForeignKey).ToList(); 
     // now we look into the FK attributes and find that the "To Role" is out current table, and the 
     // "To Property" is out current property. The underscore is a bit of an assumption that the foreign 
     // key name built by EF will be ENTITY_BLAH_BLAH 
     var thisFk = fk.Where(x => x.ReferentialConstraints[0].ToRole.Name.StartsWith(tableName + "_")) 
      .FirstOrDefault(x => x.ReferentialConstraints[0].ToProperties[0].Name == propertyName); 
     // if fkname has no results, this is not a foreign key and we are done 
     if (thisFk == null) return null; 

     // Now that we know the foriegn key, we need to lookup the Name value in the other table 

     // find the assembly 
     var assembly = Assembly.GetCallingAssembly(); 
     // build the type for the foreign key entity 
     // e.g. if the current entity is Task, and the property is StatusID, we are 
     // getting the "TaskStatus" type with reflection 
     // "User" class is an object in the Models namespace - you could just hardcode the string if you want 
     var foreignKeyType = assembly.GetType(typeof(User).Namespace + "." + 
        thisFk.ReferentialConstraints[0].FromRole.GetEntityType().Name); 

     // get the DbSet, same as: "(new DBContext()).EntityName" 
     var fkSet = Set(foreignKeyType); 
     // and find the row in that table 
     var fkItem = fkSet.Find(foreignKeyID); 

     // find the first column marked with the "IsName" attribute, otherwise default to "Name" 
     var nameColProperty = foreignKeyType.GetProperties() 
      .FirstOrDefault(p => p.GetCustomAttributes(typeof(IsNameAttribute), false).Any()); 
     string nameCol = "Name"; 
     if (nameColProperty != null) nameCol = nameColProperty.Name; 
     var nameColProperty2 = fkItem.GetType().GetProperty(nameCol); 
     if (nameColProperty2 == null) return null; 

     // get the value 
     var fkValue = nameColProperty2.GetValue(fkItem, null); 

     // and now, my brain hurts 
     return fkValue; 
    } 
0

該解決方案是基於@JamesR's answer

我的目標是讓代碼更通用,因此它可以用於連接到不同表的多個外鍵。

改進值得注意的是:

  • 我感動的是得到propertyName的foreach循環之外的外鍵列表中的代碼。由於FK列表不會根據特定屬性而改變,因此沒有理由每次都檢索新列表。如果系統中有許多FK,這可能需要一段時間,所以您不希望不必要地重複該過程。

  • 而不是硬編碼的一類特殊類型的像GetType(typeof(User),我使用檢索從FK外鍵表名:

    string lookUpTableName = thisFk.ReferentialConstraints[0].FromRole.Name;  
    

    然後,雖然引用的FK屬性名稱通常是ID,因爲它可以改變,我檢索到的FK屬性的名稱,以及:

    string lookUpPropertyName = thisFk.ReferentialConstraints[0].FromProperties[0].Name; 
    

    然後我用ObjectContext.ExecuteStoreQuery動態插上表和列名和檢索外鍵文本值。

  • 如果某個屬性是FK,我將爲原始的新值獲取FK文本值。


完整代碼:

首先,獲取系統中所有外鍵的列表。

IObjectContextAdapter contextAdapter = ((IObjectContextAdapter)this); 
MetadataWorkspace workspace = contextAdapter.ObjectContext.MetadataWorkspace; 
var items = workspace.GetItems<AssociationType>(DataSpace.CSpace); 

List<AssociationType> FKList = items == null ? null 
    : items.Where(a => a.IsForeignKey).ToList(); 

然後,循環訪問屬性列表,並在存在FK時使用外鍵值替換原始值和當前值。

foreach (string propertyName in entry.OriginalValues.PropertyNames) 
{ 
    var original = entry.OriginalValues.GetValue<object>(propertyName); 
    var current = entry.CurrentValues.GetValue<object>(propertyName); 

    if (FKList != null) 
    { 
     GetPossibleForeignKeyValues(tableName, propertyName, ref original, ref current, 
      FKList, contextAdapter); 
    } 

    if ((original == null && current != null) || 
     (original != null && !original.Equals(current))) 
    { 
     result.Add(new AuditLog() 
     { 
      UserID = UserId, 
      EventDateUTC = changeTime, 
      EventType = "M", // Modified 
      TableName = tableName, 
      RecordID = primaryKey.ToString(), 
      ColumnName = propertyName, 
      OriginalValue = original != null ? original.ToString() : "NULL", 
      NewValue = current != null ? current.ToString() : "NULL" 
     }); 
    } 
} 

這裏是真正的外鍵發現代碼:

private void GetPossibleForeignKeyValues(string tableName, string propertyName, 
    ref object originalFKValue, ref object newFKValue, 
    List<AssociationType> FKList, IObjectContextAdapter contextAdapter) 
{ 
    // If this property is part of a foreign key, look up and set the FKValue to the text 
    // value of the foreign key. Otherwise, just leave the FKValue alone. 

    // Look into the FK attributes and find that the "To Role" is out current table, 
    // and the "To Property" is out current property. 
    AssociationType thisFk = FKList.FirstOrDefault(x => 
     tableName.Contains(x.ReferentialConstraints[0].ToRole.Name) 
     && propertyName.Contains(x.ReferentialConstraints[0].ToProperties[0].Name)); 

    // If fkname has no results, this is not a foreign key and we are done. 
    if (thisFk != null) 
    { 
     // Now that we know the foriegn key, look up the Name value in the other table. 
     string lookUpTableName = thisFk.ReferentialConstraints[0].FromRole.Name; 
     string lookUpPropertyName = thisFk.ReferentialConstraints[0].FromProperties[0].Name; 

     //Assuming the FK column name is "Name". 
     //Use the idea in @JamesR's solution or some sort of LookUp table if it is not. 
     string commandText = BuildCommandText("Name", lookUpTableName, lookUpPropertyName); 

     originalFKValue = contextAdapter.ObjectContext 
      .ExecuteStoreQuery<string>(commandText, new SqlParameter("FKID", originalFKValue)) 
      .FirstOrDefault() ?? originalFKValue; 

     newFKValue = contextAdapter.ObjectContext 
      .ExecuteStoreQuery<string>(commandText, new SqlParameter("FKID", newFKValue)) 
      .FirstOrDefault() ?? originalFKValue; 

    } 
} 

這是我用來建立SQL的CommandText的方法:

private string BuildCommandText(string columnName, string lookUpTableName, 
    string lookUpPropertyName)  
{ 
    StringBuilder builder = new StringBuilder(); 

    builder.Append("SELECT "); 
    builder.Append(columnName); 
    builder.Append(" FROM "); 
    builder.Append(lookUpTableName); 
    builder.Append(" WHERE "); 
    builder.Append(lookUpPropertyName); 
    builder.Append(" = @FKID"); 

    //The result query will look something like: 
    //SELECT ColumnName FROM TableName WHERE PropertyName = @FKID 

    return builder.ToString(); 
}