0

新しいアイテムを作成するとき。設定されているすべてのフィールド値にアクセスする方法はありますか?

Entity.GetModifiedMembers()ロギング目的で更新時に変更されるフィールドの値にアクセスするために method を使用しているので、目的は、 method のように、作成時にエンティティを介して同等の結果を得ること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 に答える