C # Entity Framework Linq: выберите, где, если / иначе - PullRequest
2 голосов
/ 17 марта 2019

Можно ли сделать .Where с серией вложенных if операторов?

Вот что я хотел бы сделать:

public class Repository {
    public async Task<IQueryable<Order>> orders (int? accountId, int? userId) {
        IQueryable<Order> orders;

        orders = _context.Orders
            .Where(o =>
            {
                int filterCount = 0;
                int filterCriteriaMet = 0;

                // if the accountId param is not null
                // increment the filter counter
                // and check if this order's accountId == param
                // if so, increment filterCriteriaMet counter
                if (accountId != null)
                {
                    filterCount++;

                    if (o.AccountId == accountId)
                    {
                        filterCriteriaMet++;
                    }
                }

                // if the userId param is not null
                // increment the filter counter
                // and check if this order's userId == param
                // if so, increment filterCriteriaMet counter
                if (userId != null)
                {
                    filterCount++;

                    if (o.UserId == userId) {
                        filterCriteriaMet++;
                    }
                }

                return filterCount == filterCriteriaMet;
            });

        return orders;
    }
}

но это дает мне следующую ошибку:

Лямбда-выражение с телом оператора не может быть преобразовано в дерево выражений

1 Ответ

5 голосов
/ 17 марта 2019

Конечно!

.Where(o => AccountId != null && o.AccountId == accountId || (UserId != null && o.UserId == UserId));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...