简体   繁体   中英

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.

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?

I've looked at Expression Trees and Dynamic Linq, but I'd much rather keep it in standard linq if possible.

Thanks!

Disclaimer : I'm the owner of the project C# Eval Expression

If you want to keep the syntax similar to LINQ, I would recommend our library. The LINQ Dynamic part is free .

All you have to do is calling "WhereDynamic" instead of "Where" and keep using the same exact syntax.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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