考虑以下计划
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集合(实体框架的数据类型)并返回通用列表。它工作正常,但在某些情况下它抛出异常,因为&#34;对象无法枚举两次&#34; ...
有没有更好的方法来重写函数?
答案 0 :(得分:3)
如果您对ObjectResult的多次枚举有问题,请不要将它传递给您的方法并控制枚举:
public static void Fill<T1, T2>(List<T1> Source, List<T2> Destination)
并用
调用它Fill(objectResult.ToList(), destinationList);
顺便说一下。为什么不使用AutoMapper呢?