0

创建新项目时;有什么方法可以访问所有设置的字段值。

由于我使用Entity.GetModifiedMembers()方法来访问在更新时更改以进行日志记录的字段的值,因此目的是在创建时通过实体获得等效的结果,例如方法Entity.GetSetMembers()

所以总的来说,我只需要一个带有“成员名称”和“值”项的键值对。

例子:

public class SomethingEntity
{
    public int Id {get;set;}
    public string Name {get;set;}
    public DateTime Created {get;set;}
    public DateTime Modified {get;set;}
}

public Dictionary<string, string> GetFieldsAndValuesOfCreatedItem(object entity)
{
    //This is what I need, that can take all the objects from an entity and give
    //the property-value pairs for the object instance
    return RequieredMethod(entity);
}

public ExampleMethod()
{
    var newObject = new SomethingEntity() { Name = "SomeName", Created = DateTime.Now };
    Entity.insetOnSubmit(newObject);
    Entity.SubmitChanges();

    var resultList = GetFieldsAndValuesOfCreatedItem(newObject);

    foreach (var propertyKeyValue in resultList)
    {
        var propertyString = "Property Name: " + propertyKeyValue.Key;
        var valueString = "Value : " + propertyKeyValue.Value; 
    }
}
4

1 回答 1

1

我发现,反射是我所能找到的答案:所以这是我想出的方法:

public static Dictionary<string, string> GetFieldsAndValuesOfCreatedItem(object item)
{
    var propertyInfoList = item.GetType().GetProperties(BindingFlags.DeclaredOnly |
                                                            BindingFlags.Public |
                                                            BindingFlags.Instance);

    var list = new Dictionary<string, string>();

    foreach (var propertyInfo in propertyInfoList)
    {
        var valueObject = propertyInfo.GetValue(item, null);
        var value = valueObject != null ? valueObject.ToString() : string.Empty;

        if (!string.IsNullOrEmpty(value))
        {
            list.Add(propertyInfo.Name, value);
        }
    }

    return list;
}
于 2012-07-05T09:33:49.477 回答