Search code examples
entity-frameworklinqprojection

Project into a (list of) concrete object instead of an (list of) anonymous object


The problem simplified is as follows: in Entity Framework i am doing a join involving 3 tables, and returning the joined result set, which involves (some) fields from the 3 tables.

var query = (
        from t1 in dbCtx.TB_Entity1
        from t2 in dbCtx.TB_Entity2
             .Where(p => p.someCol  == t1.someCol && t.IsActive == true)
             .DefaultIfEmpty() //LEFT JOIN
        from t3 in dbCtx.TB_Entity3
             .Where(q => q.someCol == t2.someCol)
        where t1.IsLatest == true
        && (t1.istatus == 2 
            || t1.istatus == 3 
        )
        select new {
            t1.col100,
            t1.col101,
            t2.col200,
            t2.col201,
            t3.col300,
            t3.col301
        }).OrderByDescending(t1 => t1.ID);

var anonObjList = query.ToList();

Thus, at the end of the query I write a projection to select the fields i want.

Finally i run the query with .ToList() and get a list of Anonymous objects.

How do i modify the query to project into a List of MyConcreteClass

i.e. i want to be able to write something similar to

List<MyConcreteClass> myObjList = query.ToList();

You may assume my concrete class looks like

public class MyConcreteClass
{
    public string Col100 { get; set; }
    public string Col101 { get; set; }
    public string Col200 { get; set; }
    public string Col201 { get; set; }
    public string Col300 { get; set; }
    public string Col301 { get; set; }
}

Solution

  • You just use the object initializer syntax:

    new MyConcreteClass
    {
        Col100 = t1.col100,
        Col101 = t1.col101,
        Col200 = t2.col200,
        Col201 = t2.col201,
        Col300 = t3.col300,
        Col301 = t3.col301
    }