0
私はAutoMapperを使用してオブジェクト同士をマップしています。私のオブジェクトの1つは、他のオブジェクトのコレクションであるいくつかのプロパティを持っています。私は実行時まで何をしていなくても、さまざまなオブジェクトをマップする一般的な方法を考え出しました。これまでのサンプルコードはこれまで通りです:親オブジェクトのコレクションプロパティに動的オブジェクトを追加します。
public class Person
{
public List<Sibling> Siblings;
public List<Pet> Pets;
public List<Vehicle> Vehicles;
}
static void DoStuff(List<PersonInfo> people)
{
Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();
{
dictionary.Add(typeof(SiblingInfo), typeof(Sibling));
dictionary.Add(typeof(PetInfo), typeof(Pet));
dictionary.Add(typeof(VehicleInfo), typeof(Vehicle));
//MANY MORE ENTRIES
//.................
//END
}
using (MyEntities db = new MyEntities())
{
foreach (PersonInfo personInfo in people)
{
Person newPerson = Mapper.Map<Person>(personInfo);
foreach (PropertyInfo propertyInfo in personInfo.GetType().GetProperties())
{
if (propertyInfo.PropertyType.IsArray)
{
Array array = (Array)propertyInfo.GetValue(personInfo);
for (int i = 0; i < array.Length; i++)
{
dynamic objectInfo = array.GetValue(i);
Type sourceType = objectInfo.GetType();
Type destinationType;
if (dictionary.TryGetValue(sourceType, out destinationType)) ;
dynamic newObject = Mapper.Map(objectInfo, sourceType, destinationType);
//HOW TO ADD THE NEW OBJECT TO ITS RESPECTIVE COLLECTION???
//newPerson.Siblings.Add(newObject);
//newPerson.Pets.Add(newObject);
//newPerson.Vehicles.Add(newObject);
//newPerson.HOW_TO_ADD_THIS.Add(newObject);
}
}
}
}
//DO MORE STUFF
//........
//END
}
}
これは型に関係なく正確にマッピングします。私が苦労している問題は、このオブジェクトの適切なコレクションプロパティに新しいオブジェクトを追加する必要がある、このコードの最後です。
このコードを修正して、新しいオブジェクトを適切なコレクションに追加するにはどうすればよいですか?
リフレクションでそれぞれのコレクションプロパティを取得して、そこにオブジェクトを追加してみませんか? – Evk
@エヴァークそれは素晴らしいだろう。私はそれをするのに苦労してきました。以前は言及しなかったことをお詫び申し上げます。私は、私が試したさまざまなことのいくつかを示してきましたが、あまりにも多くの使い捨てコードがありました。 – Sesame