Search code examples
c#entity-framework-4projection

EF : Projecting data into a sub-class of a class


I'm trying to project some data into a list of POCOs where the POCO contains an instance of another type of POCO.

The two classes are Case and MyEntity, where Case has an instance of MyEntity called Client.

public class Case
{
    public int ID { get; set; }
    public string CaseReference { get; set; }
    public bool Deleted { get; set; }
    public MyEntity Client { get; set; }
}

and

public class MyEntity
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I'm trying to query it like this but it's failing reporting "Unable to create a constant value of type MyEntity":

 var result = (from c in context.cases
               where c.case_ref.Contains(caseReference)
               select new Case
               {                                      
                   ID = c.id,
                   CaseReference = c.case_ref,
                   Deleted = c.deleted,
                   Client = new MyEntity { ID = c.client.id, Name = c.client.name } 
               }).ToList();

What's the best way of doing this, am I going to have to break it down into separate queries?


Solution

  • Entity Framework's IQueryable implementation is more picky about creating new objects in objects than regular linq to objects (IEnumerable). If you first convert your query result to IEnumerable by ToList():

    context.cases.Where(c => c.case_ref.Contains(caseReference).ToList()
    

    Then you can continue creating new Case objects the way you want. (You may need to Include() Case.Client in context.cases).