0

I'm working on a generic repository for Entity Framework. To search for values I have a Find method on my repository that takes an expression. During this process I want to log the expression. I do this by getting expression.Body.

Here is my code

    public async Task<TEntity> FindFirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> expression) where TEntity : class
    {
        string expBody = expression.Body.ToString();

        // Log expBody here

        return await _context.Set<TEntity>().Where(expression).FirstOrDefaultAsync().ConfigureAwait(false);
    }

The above code works fine when testing with a hard coded condition like this.

var blogs = await uow.Repository.FindFirstOrDefault<Blog>(x => x.BlogId == 1).ConfigureAwait(false);

When I debug that above line has expBody with a value of (x.BlogId == 1)

However if I do the comparison against a variable like this:

int id = 1;
var blogs = await uow.Repository.FindFirstOrDefault<Blog>(x => x.BlogId == id).ConfigureAwait(false);

I end up getting this for expBody:

(x.BlogId == value(TestProject.ValueService+<>c__DisplayClass4_0).intId)

How can I get the actual expression body like when I'm using a hard coded value when I'm actually referencing a variable?

James
  • 523
  • 1
  • 4
  • 20
  • Seems like you have a [closure](https://stackoverflow.com/questions/595482/what-are-closures-in-c). That's how they look in an expression. – John Wu Apr 08 '20 at 22:47
  • Why are you writing a generic repository around EF? Entity framework is *already* an implementation of the generic repository and the UOW patterns. But yes, you have a closure. If you want the value you'll have to do a partial evaluation of the expression. – pinkfloydx33 Apr 08 '20 at 22:51
  • @pinkfloydx33 " If you want the value you'll have to do a partial evaluation of the expression." How do I do that? – James Apr 08 '20 at 23:22
  • @pinkfloydx33 Not having a generic repository means I would have to have a typed DbContext which doesn't work for the generic library the repository will be in. – James Apr 08 '20 at 23:25

0 Answers0