0

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!

2
  • 1
    Standard LINQ won't allow this. If you really want this (and sacrifice a lot of clarity in your code) you have to build expressions or use dynamic LINQ. Commented Apr 16, 2020 at 20:54
  • I was worried this might be the case. I tried a few Expression examples and just couldn't get this translate into one. Commented Apr 16, 2020 at 20:58

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's pretty cool. I ended up refactoring my db to avoid the awkward query which allowed me to keep it generic. I'll keep this library in mind for the future thought, pretty clean approach. Thanks for the solution anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.