首页 > 解决方案 > 如何使用带有动态字符串的实体框架 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#entity-frameworklinq

解决方案


免责声明:我是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();

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


推荐阅读