Search code examples
c#entity-frameworkentity-framework-6.1

Reuse Object Creation Code With Entity Framework - Project to new class querying only the required columns


Can the select new MobileTeamModel be refactored into a reusable method and still be read by Entity Framework? I have quite a bit of requests that need this same data and would like to reuse it but I know Entity Framework complains about this type of stuff.

  var teams = new MobileListResponse<MobileTeamModel>
            {
                List = (from e in _divisionsRepository.DataContext.DivisionTeams.Where(@where.Expand())
                    orderby e.Team.Name
                    select new MobileTeamModel
                    {
                        Id = e.Id,
                        Name = e.Team.Name,
                        Status = e.Status,
                        Paid = e.Paid,
                        Division = e.Division.Name,
                        City = e.Team.TeamAddress.Address.City,
                        StateRegion =
                            e.Team.TeamAddress.Address.StateRegionId.HasValue
                                ? e.Team.TeamAddress.Address.StateRegion.Name
                                : null
                    }).ToList()
            };

EDIT

The idea is to implement the select new MobileTeamModel { ... } in a reusable way, while having EF only query the required columns.


Solution

  • You simply have to add a constructor or a factory (static method that return a MobileTeamModel) and receives a Team.

    Then you can make a simpler query like this:

    select new MobileTeamModel(e.Team)  // parametreized constructor
    

    or this

    select MobileTeamModel.FromTeam(e.Team) // factory
    

    Finallyyou can use something like AutoMapper or ValueInjecter to project the data returned by the query to another class by using conventions or mapping.

    NOTE: I can't see how your clasees look like, but this is the basic idea.

    EDIT: getting EF to query only the necessary columns

    As for your comment, you want to reuse the construction part, and have EF only query the required columns, and not he whole entities.

    Another good explanation here: Los Techies. Efficient querying with LINQ, AutoMapper and Future queries

    To do so you must use Automapper, with Queryable Extensions.

    WHen you use this extensions, you can use a mapping from a query result to the destination class, and have EF only query the mapped columns.