使用反射、成员表达式或任何东西的动态 EF Linq 连接导航属性

我正在尝试为实体框架 (https://docs.microsoft.com/en-us/ef/core/querying/filters) 创建全局查询过滤器

而且我想对我的 dbcontext 中的每个实体应用自定义左连接。现在这个困难来自于表连接(https://www.tutorialsteacher.com/linq/linq-joining-operator-join),因为内部/外部序列的键选择器似乎必须是相同的类型(整数,字符串等)。

但是,如果我像下面这样对我的加入进行硬编码:

standardList,// inner sequence 
student => student.StandardID,// outerKeySelector
standard => standard.StandardID,// innerKeySelector
(student,standard) => new  // result selector
{
StudentName = student.StudentName,StandardName = standard.StandardName
});

我们没有问题,因为键选择器都是相同类型(int)的导航属性。伟大的!然而,

对于我的应用程序,我将以下内容插入到字典中: 实体,导航属性(例如:Student.Parent.Id)。 这作为类型存储在我的字典中:对于我这样注册的每个实体的 Expression>:

Class().Register<Person,int>(x => x.Parent.Id)

然后我希望能够使用这个循环所有实体:Using Global Query Filters for all entities

然而,在我的实现中出现的困难是,当我们循环它们时,我找不到一种方法来换入和换出键选择器,因为它们存储为不同的实体类型,这意味着当我尝试引用表达式时,它可以不加入,因为它们有两种不同的类型,即实体,实体。(即使这两个属性都是相同的类型(int)。我希望成员表达式可能会有所帮助,但我对他们没有运气,也没有运气创建一个 lambda 表达式。

我已经尝试过示例(sudo):

var x = Expression.Parameter(typeof(Person),"x");
var body = Expression.PropertyOrField(x,"Id");
var lambda = Expression.Lambda<Func<Person,int>>(body,x);

Expression<Func<TEntity,bool>> test = x => dbset<Person>.Join( dbset<Parent>,b => lambda,c => lambda 
(b,cda) => new {b,cda})
.Where(y => y.Person.Id == 1).Any()
)

var testb = typeof(TEntity).GetProperty("Id");

//I know this would join to itself but would at least join for a test. Compiles but the query cant' be translated exception probably because it says the outer and inner joins are: (object)(int)(PropertyInfo)Int32 Id.Getvalue() which I dont think translate like it says
Expression<Func<TEntity,b => (int)testb.Getvalue(b,null),c => (int)testb.Getvalue(c,null)
(b,cda})
.Where(y => y.Person.Id == 1).Any()
)



这非常令人沮丧,因为我认为实现起来不会那么复杂,我花了几天时间试图实现一些在纸面上听起来很简单的东西,只需将硬编码表达式替换为我之前创建的表达式即可!

我研究了表达式、成员表达式、lambda 编译、反射、委托,但 Google 上的所有内容现在都是紫色的。有人可以帮我指点迷津吗?

必须可以基于存储的导航属性对所有实体应用上述连接

tingfeng0922 回答:使用反射、成员表达式或任何东西的动态 EF Linq 连接导航属性

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/5820.html

大家都在问