c# - 如何使用带有动态字符串的实体框架 where 子句
问题描述
我正在尝试构建一个实体框架 linq 查询以从子对象返回父对象。
模型如下所示:
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# Eval Expression项目的所有者
如果你想保持类似于 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();
推荐阅读
- python - Python - 具有数据框来存储其他函数结果的函数
- symfony - Doctrine 查询生成器删除 x 天前创建的对象
- mysql - 带有Spring引导的Docker中的Mysql连接错误
- css - 如何使用 webpack / postcss @import '../Components/**/_partial.css' 将所有 CSS 文件导入到子目录中;
- laravel - Laravel Themes 真的在使用 Vue Js 吗?
- sockets - UNIX 域 SOCK_DGRAM 客户端 - 连接被拒绝
- python - 从具有负值和正值的熊猫数据框中绘制
- algorithm - 已解决 - 从受最大化约束的矩阵中查找逐列最大元素
- sql - 此查询提供错误。你能提供一个答案吗?
- react-native - 如何在 React-native 中使用 react-native-image-picker 和 Redux