Program to convert Entity Frameworks ObjectResult to Generic List

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 11398
I have a requirement where I need to convert a ObjectResult of Entity Framework to Generic list . Here is my attempt

public class Utility
   
{
       
/// <summary>
       
/// Function: ToList
       
/// Converts ObjectResult to Generic List
       
/// </summary>
       
/// <typeparam name="T1"></typeparam>
       
/// <typeparam name="T2"></typeparam>
       
/// <param name="Source"></param>
       
/// <param name="Destination"></param>
       
public static void ToList<T1, T2>(ObjectResult<T1> Source, List<T2> Destination) where T2 : new()
       
{
           
Destination.AddRange(Source.Select(CreateMapping<T1, T2>()));
       
}      

       
/// <summary>
       
/// CreateMapping
       
/// Creates the mapping
       
/// </summary>
       
/// <typeparam name="T1"></typeparam>
       
/// <typeparam name="T2"></typeparam>
       
/// <returns></returns>
       
private 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.ToUpper() equals destinationProperty.Name.ToUpper()
                             
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;
           
};
       
}
   
}


Usage:

First create an entity say (Employee)

public class Employee
{
       
public int EmpId { get; set; }
       
public string EmpName { get; set; }
               
public string EmpAddress { get; set; }
               
public string EmpPhoneNumber { get; set; }
       
}


Then invoke the function as under

var lstEmployee= new List<Employee>();

//Obtain the data from EntityFramework. This will give the data as ObjectResult  format
var lstEmployeeDataFromEntitiFramework = context.GetEmployeeRecords();

//Do the transformation
Utility.ToList(lstEmployeeDataFromEntitiFramework, lstEmployee);


Hope this will be helpful.

Comments or Responses

Login to post response