Reputation: 6409
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?
Upvotes: 0
Views: 166
Reputation: 6409
Following on from Gert's answer, I thought I'd post the answer in Query Expression syntax for anyone else having this problem.
Note that I had to add a bit of checking to handle there being no data in the client table:
var result = (from c2 in ((from c1 in context.cases
where c1.case_ref.Contains(caseReference)
select c1).ToList())
select new Case
{
ID = c2.id,
CaseReference = c2.case_ref,
Deleted = c2.deleted,
Client = (c2.client_id != null ? new MyEntity { ID = c2.client.ID, Name = c2.client.name } : null)
}).ToList();
Upvotes: 1
Reputation: 109255
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
).
Upvotes: 1