We're using Entity Framework with dynamic Linq expressions to select data form the database, in which the following entities are defined:
public class Entity1
{
int Id { get; set; }
string Somedata1 { get; set; }
}
public class Entity2
{
int Id { get; set; }
string Somedata2 { get; set; }
IList<EntityLink> LinkedEntities1 { get; set; }
}
public class EntityLink
{
int Id { get; set; }
Entity1 ent1 { get; set; }
Entity2 ent2 { get; set; }
}
The entities Entity1
and Entity2
have an n-n
relationship.
To dynamically select data form Entity1
we use (where selectExpression
is defined as Expression<Func<Entity1, object>>
)
var selectExpression = await modelEntity1.GetSelectExpression(); // model for `Entity1`
return await dbcontext.Entity1
.AsQueryable()
.Where(g => ...)
.Select(selectExpression)
.ToListAsync();
But in another routine I want to use the same selectExpression
to select the data from Entity1
when enumerating the 'linked' records of Entity2
:
var selectExpression = await modelEntity1.GetSelectExpression();
return await dbcontext.Entity2
.AsQueryable()
.Where(e2 => ...)
.Select(e2 => new {
Id = e2.Id,
// etc.
ChildData = e2.LinkedEntities1.Select(l => new {
LinkId = l.Id,
LinkData = l.ent1.Select(selectExpression), // <- Does not compile as no 'Select' method exists
}),
})
.ToListAsync();