简体   繁体   English

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

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

I am trying to build an Entity Framework linq query to return the parent object from a child object.我正在尝试构建一个实体框架 linq 查询以从子 object 返回父 object。

The models look like this:模型如下所示:

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

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

And my query looks like this:我的查询如下所示:

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();

Is there anyway to make the reference to "Children" dynamic and use {_foreignKeyName} instead?无论如何要动态引用“儿童”并使用{_foreignKeyName}吗?

I've looked at Expression Trees and Dynamic Linq, but I'd much rather keep it in standard linq if possible.我查看了表达式树和动态 Linq,但如果可能的话,我宁愿将其保留在标准 linq 中。

Thanks!谢谢!

Disclaimer : I'm the owner of the project C# Eval Expression免责声明:我是项目C# 评估表达式的所有者

If you want to keep the syntax similar to LINQ, I would recommend our library.如果你想保持类似于 LINQ 的语法,我会推荐我们的库。 The LINQ Dynamic part is free . LINQ 动态部分是免费的

All you have to do is calling "WhereDynamic" instead of "Where" and keep using the same exact syntax.您所要做的就是调用“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 Dynamic: https://eval-expression.net/linq-dynamic LINQ 动态: https://eval-expression.net/linq-dynamic

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

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