MVC 5 Getting the DisplayFormatAttribute of DbEntry

本文关键字:of DbEntry DisplayFormatAttribute the Getting MVC | 更新日期: 2023-09-27 18:20:48

我有一个审计方法,可以将更改记录到我的数据库中。

该方法看起来(abit)简化如下

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

在字段的元数据属性中,我在调试会话中的局部变量中找到了该变量。但仅在"this"变量中。对于每个不同的数据库条目,这必须是动态的。

MVC 5 Getting the DisplayFormatAttribute of DbEntry

只需更换

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

通过

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

事实上,"this"是当前的类,它不包含要记录的实体的属性