0

i'm having some trouble trying to do a expression with a generic type

What i'm trying to do is to create an expression using a generic for my entity types because i want to build a method to build dynamic querys, something like this:

 public static void executeQuery()
    {
        using (BookStore context = new BookStore())
        {
            DbSet<Author> table = GetEntity<Author>(context);

            var list =  table.AsExpandable().Where(a => DynamicQueryUtility.GetLastId<Author>().Invoke(a,"AuthorId")<10).ToList();

            foreach (var author in list)
            {
                Console.WriteLine(author.ToString());
            }`enter code here`
        }
    }

i get the next exception:

System.InvalidOperationException: 'The LINQ expression 'DbSet() .Where(a => (int)a.GetType().GetProperty("AuthorId").GetValue( obj: a, index: null) < 10)' 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.

The method i'm calling is the next one:

public static Expression<Func<TEntity,string, int>> GetLastId<TEntity>()
where TEntity : class
{
   return (x,y) => (int)x.GetType().GetProperty(y).GetValue(x,null);
}

the Author entity has just 2 properties, AuthorId type int and Name type string

  • 1
    While it is wrong, currently I do not see any benefits of using this method, `EF.Property` more suitable here. What you are trying to build dynamically? – Svyatoslav Danyliv Nov 08 '21 at 11:01
  • If you are trying to build a query dynamically, you might also want to look at https://github.com/zzzprojects/System.Linq.Dynamic.Core . It can cover most parts for you – Abbas Cyclewala Nov 08 '21 at 12:14

0 Answers0