Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

C# cannot use .Any() when build Expression for querying with EF core

$
0
0

I'm trying to build an Expression<Func<T, bool>>:

public static Expression<Func<T, bool>> CreateAny<T, TAnother>(        Expression<Func<T, IEnumerable<TAnother>>> collectionPropertyExpression,        Expression<Func<TAnother, bool>> anyPredidate    )    {        var param = Expression.Parameter(typeof(T), collectionPropertyExpression.Parameters.Single().Name);        var anyMethodInfo = typeof(Enumerable)            .GetMethods(BindingFlags.Public | BindingFlags.Static)            .Single(m => m.Name == "Any" && m.GetParameters().Length == 2)            .MakeGenericMethod(typeof(TAnother));        var anyCallExpression = Expression.Call(            anyMethodInfo,            collectionPropertyExpression.Body,            Expression.Lambda<Func<TAnother, bool>>(anyPredidate.Body, anyPredidate.Parameters.Single())        );        return Expression.Lambda<Func<T, bool>>(anyCallExpression, param);    }

This is how i use it:

public async Task<IActionResult> Tests()   {        /*I want it returns something like:            a => a.ReceivedNotifications.Any(noti => noti.Status == NotificationStatus.Read)        */        var exp = ExpressionHelper.CreateAny<Account, AccountNotification>(            a => a.ReceivedNotifications,            noti => noti.Status == NotificationStatus.Read        );        logger.LogInformation("{0}", exp); // a => a.ReceivedNotifications.Any(noti => (Convert(noti.Status, Int32) == 2))        return Ok(await unitOfWork.Accounts.GetAsync(expression: exp)); // error here    }

and I got an error:
System.InvalidOperationException: The LINQ expression 'a' 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.

I need to know why I have an error here and is there any solution for this?
Thank you in advance.


Viewing all articles
Browse latest Browse all 12111

Trending Articles