C#实体框架Linq:选择If / Else

JED*_*JED 2 c# linq entity-framework

是否可以对.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我以下错误:

具有语句主体的Lambda表达式无法转换为表达式树

Dav*_*ali 5

当然!

.Where(o => AccountId != null && o.AccountId == accountId || (UserId != null && o.UserId == UserId));
Run Code Online (Sandbox Code Playgroud)