2012-01-22 54 views
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集合(實體框架的數據類型),並返回一個泛型列表。它工作正常,但在某些情況下,它拋出異常爲「對象不能枚舉兩次」...

有沒有更好的方法來重寫函數?

+0

那些「某些情況」是什麼?你是否有機會爲相同的'ObjectResult'調用'Fill'兩次? – hvd

回答

3

如果你有ObjectResult的多個列舉的問題根本就沒有把它傳遞給你的方法和控制枚舉自己:

public static void Fill<T1, T2>(List<T1> Source, List<T2> Destination) 

Fill(objectResult.ToList(), destinationList); 

順便說一句調用它。爲什麼不用AutoMapper代替?