Search code examples
entity-frameworkc#-4.0reflectionextension-methodsprojection

auto projection in entity framework


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?


Solution

  • 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.