LINQ 列表变量和列表中的数据可能为空

LINQ Where data in list variable and list is maybe null

我有一个列表,其中包含需要与数据库进行比较的所有值

from staff in this.unitOfWork.StaffRepository.Data
where officeIds.Contains(staff.OfficeId)

officeIds 有 int[] 类型,officeIds 可以为空。 officeIds为空怎么办?

我试过了

where officeIds != null && officeIds.Contains(staff.OfficeId)

但是没用。它抛出异常

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: Cannot compare elements of type 'System.Int32[]'. Only primitive types, enumeration types and entity types are supported.

感谢haim770的建议,以下是他的评论:

The officeIds array is there so that Linq to Entities would be able to emit an SQL IN(..., ...) operator, checking for its nullity is not something that the provider is supposed to be doing.
You better always initialize officeIds to an empty array (officeIds = new int[]) or append the where clause only after you check for nullity (the latter approach sounds more sensible to me)

这里我们应该跳出框框思考,而不是关注如何在 where 语句中检查 null。

问题陈述:

from staff in this.unitOfWork.StaffRepository.Data
where officeIds.Contains(staff.OfficeId)

以下in接受IQueryable。我们可以从 from

的外部网站查看
var query = this.unitOfWork.StaffRepository.Data
if(list != null && list.Count > 0)
    query = query.Where("condition")

from staff in query
where *continue other conditions*
select ...