NoStuff
NoStuff

Reputation: 63

.Net Core 5 Rest Api Entity Framework Linq Expression Translation Error While Getting Record List From Controller

I am working on a project and I got an error while getting queried list. I will tell on code block below.

//AT REPOSITORY SIDE THIS FUNCTION GETS FILTERED LIST OF RECORDS
        public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter)
        {
            using (var context=new MyContext()){
                return context.Set<TEntity>().Where(filter).ToList();
            }
        }
//AT ENTITY SIDE THIS FUNCTION CHECKS IF ALL PROPERTIES ARE EQUAL WITH THE GIVEN OBJECT
        public bool PublicPropertiesEqual(object which) 
        {
            var type = this.GetType();
            var whichType = which.GetType();
            var whichProperties = whichType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if(whichProperties.Any(x => x.Name == pi.Name)){
                    object selfValue = type.GetProperty(pi.Name).GetValue(this, null);
                    object whichValue = type.GetProperty(pi.Name).GetValue(which,null);
                    if (selfValue != whichValue && (selfValue == null || !selfValue.Equals(whichValue)))
                    {
                        return false;
                    }
                }
            }
            return true;
        }
//AT CONTROLLER SIDE ONLY CALLED REPO GETLIST FUNCTION WITH GIVEN FILTER
        [HttpGet]
        public IActionResult GetList([FromQuery] TEntity  query)
        {
            List<TEntity> res = _repo.GetList(x = x.PublicPropertiesEqual(query));
            return Ok(res);
        }

PROBLEM

When I execute the code I get an error like that

InvalidOperationException: The LINQ expression 'DbSet() .Where(c => c.PublicPropertiesEqual(__query_0))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

So I cant get records from database. I tried to write custom expression tree showed below at the controller side and it also doesn't work.

        [HttpGet]
        public IActionResult GetList([FromQuery] TEntity  query)
        {
            var param = Expression.Parameter(typeof(TEntity));
            var lambda = Expression.Lambda<Func<TEntity,bool>>(
                Expression.Call(
                    param, 
                    _entityType.GetMethod("PublicPropertiesEqual"),
                    Expression.Constant(query)
                ),
                param
            );
            List<TEntity> res = _repo.GetList(lambda);
            return Ok(res);
        }

And the error after executed this code

InvalidOperationException: The LINQ expression 'DbSet() .Where(c => c.PublicPropertiesEqual(Customer))' could not be translated. REST OF THE ERROR IS SAME ABOVE...

As a conclusion, how can I filter the query with using PublicPropertiesEqual(object) function ?

Upvotes: 0

Views: 621

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27406

It is easy to write such function, but you have to filter out navigation properties by yourself:

public static Expression<Func<T, bool>> PublicPropertiesEqual<T>(T entity)
{
    var props = typeof(T).GetProperties();
    var entityParam = Expression.Parameter(typeof(T), "e");
    var entityExpr = Expression.Constant(entity);

    var equality = props.Select(p => Expression.Equal(
        Expression.MakeMemberAccess(entityParam, p),
        Expression.MakeMemberAccess(entityExpr, p)
    ));

    var predicate = equality.Aggregate(Expression.AndAlso);
    return Expression.Lambda<Func<T, bool>>(predicate, entityParam);
}

Usage is simple:

List<TEntity> res = _repo.GetList(PublicPropertiesEqual(query));

Anyway if you have access to DbContext better to pass it to the function and reuse IModel information.

public static Expression<Func<T, bool>> PublicPropertiesEqual<T>(DbContext ctx, T entity)
{
    var et = ctx.Model.FindEntityType(typeof(T));
    if (et == null)
        throw new InvalidOperationException();

    var props = et.GetProperties();
    var entityParam = Expression.Parameter(typeof(T), "e");
    var entityExpr = Expression.Constant(entity);

    var equality = props
        .Where(p => !p.IsForeignKey() && !p.IsIndexerProperty())
        .Select(p => Expression.Equal(
            Expression.MakeMemberAccess(entityParam, p.PropertyInfo),
            Expression.MakeMemberAccess(entityExpr, p.PropertyInfo)
        ));

    var predicate = equality.Aggregate(Expression.AndAlso);
    return Expression.Lambda<Func<T, bool>>(predicate, entityParam);
}

Upvotes: 1

Related Questions