MVC 5获取DbEntry的DisplayFormatAttribute

时间:2014-09-04 12:40:40

标签: c# asp.net-mvc entity-framework

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

该方法看起来(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());

            }
        }
    }
}

我在该字段的元数据属性中的调试会话中找到了本地变量。但只有在&#34;这个&#34;变量。对于每个不同的DBentries,这必须是动态的。

1 个答案:

答案 0 :(得分:1)

只需替换

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

通过

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

确实,&#34;这个&#34;是当前类,它不包含要记录的实体的属性