繁体   English   中英

如何使用带有动态字符串的实体框架 where 子句

[英]How to use Entity Framework where clause with a dynamic string

我正在尝试构建一个实体框架 linq 查询以从子 object 返回父 object。

模型如下所示:

public class Parent
{
   Guid Id {get; set;}
   List<Child> Children {get; set;}
}

public class Child
{
    Guid Id {get; set;}
}

我的查询如下所示:

string _foreignKeyName = "Children"
Guid existingChildId = "{some existing guid}"

var parent = _context.Set<Parent>()
                     .Include(_foreignKeyName)
                     .Where(x => x.Children // <--- I would like to make "Children" dynamic
                     .Where(y => y.Id == existingChildId).Any()) 
                     .FirstAsync();

无论如何要动态引用“儿童”并使用{_foreignKeyName}吗?

我查看了表达式树和动态 Linq,但如果可能的话,我宁愿将其保留在标准 linq 中。

谢谢!

免责声明:我是项目C# 评估表达式的所有者

如果你想保持类似于 LINQ 的语法,我会推荐我们的库。 LINQ 动态部分是免费的

您所要做的就是调用“WhereDynamic”而不是“Where”并继续使用相同的语法。

string _foreignKeyName = "Children"
Guid existingChildId = "{some existing guid}"

var parent = _context.Set<Parent>()
                     .Include(_foreignKeyName)
                     .WhereDynamic(x => "x.Children")
                     .Where(y => y.Id == existingChildId).Any()) 
                     .FirstAsync();

LINQ 动态: https://eval-expression.net/linq-dynamic

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM