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?