0
考虑下面的程序将通用ObjectResult集合(实体框架数据类型)转换为通用列表集合的更好方法?
public static void Fill<T1, T2>(ObjectResult<T1> Source, List<T2> Destination)
where T2 : new()
{
Destination.AddRange(Source.Select(CreateMapping<T1, T2>()));
}
public static Func<T1, T2> CreateMapping<T1, T2>()
where T2 : new()
{
var typeOfSource = typeof(T1);
var typeOfDestination = typeof(T2);
// use reflection to get a list of the properties on the source and destination types
var sourceProperties = typeOfSource.GetProperties();
var destinationProperties = typeOfDestination.GetProperties();
// join the source properties with the destination properties based on name
var properties = from sourceProperty in sourceProperties
join destinationProperty in destinationProperties
on sourceProperty.Name equals destinationProperty.Name
select new { SourceProperty = sourceProperty, DestinationProperty = destinationProperty };
return (x) =>
{
var y = new T2();
foreach (var property in properties)
{
var value = property.SourceProperty.GetValue(x, null);
property.DestinationProperty.SetValue(y, value, null);
}
return y;
};
}
当我们接受一个ObjectResult集合(实体框架的数据类型),并返回一个泛型列表。它工作正常,但在某些情况下,它抛出异常为“对象不能枚举两次”...
有没有更好的方法来重写函数?
那些“某些情况”是什么?你是否有机会为相同的'ObjectResult'调用'Fill'两次? – hvd