0

Overview:

I am currently working on a GraphQL API and I'm writing a fluent interface for creating joins between database entities inside my application and I would like to create some reusable "blocks" that use generic repository.

The problem:

Provided that I have a Func<TEntity, TKey> that will be used to select a field from the entity, is there some easy way to use it inside a Where expression to construct a condition using that field?

Plese see the pseudocode below to see what I mean:

public class Repository<TEntity> {

    private Func<TEntity, Guid> keySelector;

    // ...
    
    public List<TEntity> GetEntitiesByKeys(Guid parentId, IEnumerable<Guid> keys) {
        return context.Set<TEntity>
            .Where(x => x.ParentId == parentId && keys.Contains(keySelector(x)) // Can I do something to use the keySelector here?
            .ToList(); 
    }
}
PJDev
  • 951
  • 5
  • 20
  • `Func<..>`, no, but `Expression>`, yes, depending on what exactly you've put into the expression. An expression usable with EF needs to be able to be translated to SQL, otherwise you will have to run as much as you can in the database, and then run the rest in your client with .NET code. – Lasse V. Karlsen Jul 26 '20 at 19:31

1 Answers1

0

It is, but you will need to provide them as an Expression<Func<TEntity, TKey>> and might need to manually put them in the expression tree.

If you need some sample code to get you started, just say so in the comments and I update my answer accordingly.

lauxjpn
  • 4,749
  • 1
  • 20
  • 40
  • Thanks, that's what I actually finished up with. I changed the Funcs to expressions and used an `Expression.Call` to create the "Contains" expression as shown here: https://stackoverflow.com/questions/19052507/how-to-use-a-func-in-an-expression-with-linq-to-entity-framework – PJDev Jul 26 '20 at 20:07
  • Awesome, I would have implemented it in a similar way (just with `IEnumerable` instead of `ICollection` and of course with the `x.ParentId == parentId &&` part). – lauxjpn Jul 26 '20 at 20:56