Reputation: 27595
Is there anyway to create a auto projection in entity framework? see please:
public class Person{
public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string FatherName {get; set;}
public string City {get; set;}
public string AddressLine {get; set;}
public string Something {get; set;}
}
public class PersonNameModel{
public string FirstName {get; set;}
public string LastName {get; set;}
public string FatherName {get; set;}
}
public class PersonAddressModel{
public string City {get; set;}
public string AddressLine {get; set;}
}
// etc...
I mean I be able to replace normal projection like:
context.Persons.Select(t => new PersonNameModel{ FirstName = t.FirstName /* etc */ });
whit an extension method that can use reflection and create an auto projection like:
public static class MyExtensions{
public static IQueryable<T> AutoSelect<T, TProject>(this IQueryable<T> q){
// read TProject type in reflection
// create a projection as a IQueryable<T>
}
}
Is there any way? I googled it, but didn't find any resource. Can you guide me please?
Upvotes: 0
Views: 676
Reputation: 2036
Yes, it's possible to auto project entity framework entities to some Dto. See one of implementations here https://gist.github.com/1367880
You can use it as:
context.Persons.Project().To<PersonNameModel>().ToList();
In that case the db query will be generated to select only required columns (specified by PersonNameModel).
If you want just to map query results (that retrieved objects), so EmitMapper or AutoMapper should be your choice.
Upvotes: 1
Reputation: 887
If I understand correctly what you want is a mapping between objects, use Automapper it would do the mapping for you
http://www.codeproject.com/Articles/61629/AutoMapper
git hub path https://github.com/AutoMapper/AutoMapper
Upvotes: 0