简体   繁体   English

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

[英]C# Entity Framework Linq: Select Where If/Else

Is it possible to do a .Where with a series of nested if statements? 是否可以使用一系列嵌套的if语句在.Where进行操作?

Here's what I'd like to do: 这是我想做的:

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;
    }
}

but this gives me the following error: 但这给了我以下错误:

A lambda expression with a statement body cannot be converted to an expression tree 具有语句主体的Lambda表达式无法转换为表达式树

当然!

.Where(o => AccountId != null && o.AccountId == accountId || (UserId != null && o.UserId == UserId));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM