0

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();
Servy
  • 202,030
  • 26
  • 332
  • 449
R. Hoek
  • 916
  • 8
  • 27
  • What is the exact compiler error? ("this isn't possible" is not very informative). – Olivier Jacot-Descombes Jul 01 '21 at 14:38
  • @OlivierJacot-Descombes yes, your right - I've updated the comment to note is cannot compile as the `Select` method doesn't exist - so I'm looking for something that is available/can be used. – R. Hoek Jul 01 '21 at 15:01
  • `ent1` is not of type `IQueryable` but of type `Entity1` which doesn't have a `Select` {extension} method. Replace `l.ent1.Select(selectExpression)` by `selectExpression(l.ent1)` – Orace Jul 02 '21 at 19:13
  • @Orace That won't even compile. – Servy Jul 02 '21 at 19:56
  • @Servy you are right. That's what makes this question interesting : how to apply a select expression to a single object inside an expression. – Orace Jul 02 '21 at 20:01
  • @Servy, and you already give a response to it: https://stackoverflow.com/a/32827053/361177 – Orace Jul 02 '21 at 20:06
  • Thanks for the ideas and samples - for now we’ve duplicated the code to get the same result, but I’ll look in to this asa I have the time for it. – R. Hoek Jul 05 '21 at 20:06

1 Answers1

-1

Try changing your query to actually include the child entities:

dbcontext.Entity2.Include(x=>x.LinkedEntities1)

  • Since I don't want to just include all data regarding the `LinkedEntities1`, but only the specific members returned using the `selectExpression`, this isn't an option. – R. Hoek Jul 01 '21 at 15:03