I am trying to dynamically build some sql queries depending on the given configuration only for queries of the necessary data:
When writing a simple linq, it will look like this:
var data = dbContext
.TableOne
.Select(t1 => new TableOneSelect
{
TableOneId = t1.TableOneId,
TableOneTableTwoReference = new[] { TableOne.FirstTableTwoReference.Invoke(t1) }
.Select(t2 => new TableTwoSelect
{
TableTowId = (Guid?)t2.TableTwoId,
}).FirstOrDefault(),
});
whereas it TableOne.FirstTableTwoReference.Invoke(t1)
is determined
public static Expression<Func<TableOne, TableTwo>> FirstTableTwoReference => (t1) => t1.TableTwoReferences.FirstOrDefault();
Currently, to build a dynamic TableOne table, the following exists:
public Expression<Func<TableOne, TableOneSelect>> Init(TableOneConfig cfg)
{
var memberBindings = new List<MemberBinding>();
var selectType = typeof(TableOneSelect);
var newExpression = Expression.New(selectType);
var theEntity = Expression.Parameter(typeof(TableOne), "t1");
if (cfg.Select("TableOneId"))
memberBindings.Add(Expression.Bind(selectType.GetProperty("TableOneId"), Expression.Property(theEntity, nameof("TableOneId"))));
var memberInit = Expression.MemberInit(newExpression, memberBindings);
return Expression.Lambda<Func<tblTournament, EventResourceSelect>>(memberInit, theEntity);
}
same for TableTwo
(different properties and another db table).
This I can dynamically call like this:
dbContext.TableOne.Select (t => TableOneHelper.Init (cfg) .Invoke (t1));
whereas Invoke
- this value is from LinqKit
.
But I am stuck with the inside for TableOneTableTwoReference
where I need to make an listing to call Init
from TableTwoHelper
, but I donβt understand how this can be achieved.
, Expression.NewArrayInit(typeof(TableTwo), ...)
. , t1.TableTwoReferences.FirstOrDefault()
, Select
on.