LINQ - 无法使用WHERE条件创建

时间:2012-03-02 12:55:15

标签: c# linq asp.net-mvc-3

我有以下方法:

    public DataTable.DataTablesPage<DataTable.UserModel> DataTableUserListByAttendees(int geoArea, int CurrentUserID)
    {
        var result = from i in _dbContext.Users
                     where i.GeographicalAreas.Any(p => p.GeoAreaID == geoArea)
                     select new DataTable.UserModel()
                     {
                         ID = i.ID,
                         Company = i.Company,
                         DCMember = (i.UserId != null),
                         FirstName = i.FirstName,
                         LastName = i.LastName
                     };

}

它工作正常,但它返回没有设置geoArea proeprty的实体。

    public DataTable.DataTablesPage<DataTable.UserModel> DataTableUserListByAttendees(int? geoArea, int CurrentUserID)
    {
        var result = from i in _dbContext.Users
                     where i.GeographicalAreas.Any(p => p.GeoAreaID == geoArea)
                     select new DataTable.UserModel()
                     {
                         ID = i.ID,
                         Company = i.Company,
                         DCMember = (i.UserId != null),
                         FirstName = i.FirstName,
                         LastName = i.LastName
                     };

}

如何更改查询,使其仅返回设置了geoArea属性的实体(又名非空)。

2 个答案:

答案 0 :(得分:4)

where (geoArea == null) || i.GeographicalAreas.Any(p => p.GeoAreaID == geoArea)

或有条件地添加查询的位置

答案 1 :(得分:3)

那应该是

where geoArea == null || i.GeographicalAreas.Any(p => p.GeoAreaID == (int)geoArea)