作者:捕风的水中龙_106 | 来源:互联网 | 2023-02-07 21:20
我正在尝试动态构建一些sql查询,具体取决于给定的配置,只查询所需的数据:
在编写简单的linq时,它看起来像这样:
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,
// ... some more properties of t2
}).FirstOrDefault(),
// ... some more properties of t1
});
而TableOne.FirstTableTwoReference.Invoke(t1)
定义
public static Expression> FirstTableTwoReference => (t1) => t1.TableTwoReferences.FirstOrDefault();
目前,我有以下动态构建TableOne-part:
public Expression> Init(TableOneConfig cfg)
{
var memberBindings = new List();
var selectType = typeof(TableOneSelect);
var newExpression = Expression.New(selectType);
var theEntity = Expression.Parameter(typeof(TableOne), "t1");
// decide if the property is needed and add to the object-initializer
if (cfg.Select("TableOneId"))
memberBindings.Add(Expression.Bind(selectType.GetProperty("TableOneId"), Expression.Property(theEntity, nameof("TableOneId"))));
// ... check other properties of TableOneSelect depending on given config
var memberInit = Expression.MemberInit(newExpression, memberBindings);
return Expression.Lambda>(memberInit, theEntity);
}
为相同TableTwo
(不同的性质和不同的DB-表).
我可以像这样动态调用
dbContext.TableOne.Select(t => TableOneHelper.Init(cfg).Invoke(t1));
而Invoke
来自LinqKit
.
但是我对内部部分感到困惑,TableOneTableTwoReference
因为我需要在其中进行枚举来调用它Init
,TableTwoHelper
但我不明白这是如何实现的.
我想Expression.NewArrayInit(typeof(TableTwo), ...)
这将是第一步.但我仍然陷入如何传递t1.TableTwoReferences.FirstOrDefault()
给这个调用Select
on的数组.