2011-08-05 6 views
2

これは、私がカスタムオブジェクトに1つのオブジェクト(Entity)の "コピー"を作成する私のコードです。
ソースとターゲットの両方に同じ名前のプロパティだけをコピーします。リフレクションとextesnionメソッドを使用してオブジェクト間のプロパティをコピー

私の問題は、エンティティが別のエンティティにナビゲートしている場合です。このケースでは、カスタムクラスのプロパティの上に追加するカスタム属性を追加しました。

のように例えばカスタムクラスに見える:私は(ネストされたオブジェクトをコピーするために)再び拡張メソッドを呼び出すしようとするタイプが実行時に決定されるため問題は、targetProp.CopyPropertiesFrom(sourceProp);ラインである

public class CourseModel:BaseDataItemModel 
{ 
    public int CourseNumber { get; set; } 

    public string Name { get; set; } 

    LecturerModel lecturer; 

    [PropertySubEntity] 
    public LecturerModel Lecturer 
    { 
     get { return lecturer; } 
     set { lecturer = value; } 
    } 

    public CourseModel() 
    { 
     lecturer = new LecturerModel(); 
    } 

} 

コンパイル時に拡張メソッドを解決できませんでした。

たぶん私はあなたが最初にキャストする必要があります...

public static void CopyPropertiesFrom(this BaseDataItemModel targetObject, object source) 
{ 
    PropertyInfo[] allProporties = source.GetType().GetProperties(); 
    PropertyInfo targetProperty; 

    foreach (PropertyInfo fromProp in allProporties) 
    { 
     targetProperty = targetObject.GetType().GetProperty(fromProp.Name); 
     if (targetProperty == null) continue; 
     if (!targetProperty.CanWrite) continue; 

    //check if property in target class marked with SkipProperty Attribute 
    if (targetProperty.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length != 0) continue; 

    if (targetProperty.GetCustomAttributes(typeof(PropertySubEntity), true).Length != 0) 
    { 
     //Type pType = targetProperty.PropertyType; 
     var targetProp = targetProperty.GetValue(targetObject, null); 
     var sourceProp = fromProp.GetValue(source, null); 

     targetProp.CopyPropertiesFrom(sourceProp); // <== PROBLEM HERE 
     //targetProperty.SetValue(targetObject, sourceEntity, null); 

    } 
     else 
      targetProperty.SetValue(targetObject, fromProp.GetValue(source, null), null); 
    } 
} 
+0

ValueInjectorはあなたの時間を節約するかもしれませんhttp://valueinjecter.codeplex.com/ – Brook

答えて

1

何かが欠けています。

((BaseDataItemModel)targetProp).CopyPropertiesFrom(sourceProp); 
+0

LOL、unbelivable私はそれを前に試してみましたが、うまくいかなかったので、もう一度試しました。講師はBaseDataItemModelから継承していません... Ps(BaseDataItemModel)sourcePropが間違っていますsourcePropがEFエンティティ(BaseDataItemModelから継承されません) – offer

0

あなたはとてもあなたが(編集:エージェント-Jの答えのように)、その上に拡張メソッドを呼び出すことができますBaseDataItemModeltargetPropertyをキャストする必要があるか、そうでなければ、あなただけでは、基本クラスを忘れることができます。反射アルゴリズムにはなぜそれが必要ですか?それはどんなクラスでも機能し、純粋にプロパティの属性によって指示されます。

objectで動作する場合は、拡張メソッドではありません。

+0

または少なくとも特定の名前空間でそれを分離して、特定の制約された領域。 – asawyer

+0

BaseDataItemModelから継承するオブジェクトに対してのみ、拡張機能を制限したい – offer

関連する問題