2012-01-24 5 views
2

ジェネリッククラスを使用して、ObjectContextにジェネリックアップデートメソッドを作成したいと思います。私はすべてのプロパティをループし、ジェネリックな更新メソッドに渡すジェネリックエンティティに基づいてそれらを更新する必要があります。更新方法:EF ObjectContext内の汎用エンティティのプロパティを更新するにはどうすればよいですか?

public void Update(T entity) 
{ 
    if (entity == null) 
    { 
     throw new ArgumentNullException("entity"); 
    } 

    var propertiesFromNewEntity = entity.GetType().GetProperties(); 

    // I've a method that return a entity by Id, and all my entities inherits from 
    // a AbstractEntity that have a property Id. 
    var currentEntity = this.SelectById(entity.Id).FirstOrDefault(); 

    if (currentEntity == null) 
    { 
     throw new ObjectNotFoundException("The entity was not found. Verify if the Id was passed properly."); 
    } 

    var propertiesFromCurrentEntity = currentEntity.GetType().GetProperties(); 

    for (int i = 0; i < propertiesFromCurrentEntity.Length; i++) 
    { 
     propertiesFromCurrentEntity.SetValue(propertiesFromNewEntity.GetValue(i), i); 
    } 
} 

ただし、プロパティが値渡しされているため、これは機能しません。だから、現在のエンティティのプロパティを変更する方法がありますか?

OBS:更新、挿入、削除メソッドの後、フレームワークはmyContext.SaveChanges()を呼び出します。

+1

あなたはプロパティの配列でSetValueを呼び出しています...これはあなたが意図したものではないと思います;) –

答えて

5

値をentityからcurrentEntityに設定すると仮定します(それ以外の場合は逆の値を使用します)。あなたは自分のSetValueGetValueメソッドを使用する必要がPropertyInfoオブジェクトを持っているとき

propertiesFromCurrentEntity[i].SetValue(
    currentEntity, propertiesFromNewEntity[i].GetValue(entity, null), null); 
0

は、または設定された値を取得します。

関連する問題