实体框架动态查询表达式被忽略

时间:2015-07-10 18:27:23

标签: c# linq entity-framework

我有一个操作,它采用可序列化的QueryModel并将其转换为要传递给Entity Framework的Expression。我对数据库的查询如下:

    public IEnumerable<PhotoVerifySessionOverview> FindSessions(Expression<Func<vwPhotoVerifySession, bool>> predicate, PaginationModel model)
    {

        var sessions =  Context.vwPhotoVerifySessions
            .AsQueryable()
            .Where(predicate)
            .OrderBy(string.Format("{0} {1}", model.OrderByColumn, model.OrderByDirection))
            .Skip(model.Offset)
            .Take(model.PageSize);

        return Mapper.Map<IEnumerable<PhotoVerifySessionOverview>>(sessions);
    }

和我的谓词构建器看起来像:

        var predicate = PredicateBuilder.True<vwPhotoVerifySession>();

        //Add the tenant to the where clause
        if (model.TenantId.HasValue)
            predicate.And(p => p.TenantId == model.TenantId.Value);
        else
            predicate.And(p => p.TenantReferenceId == model.TenantReferenceId);

        //Add a date range if one is present
        if (model.CreatedOnRange != default(DateRange))
        {
            var endDate = model.CreatedOnRange.End == default(DateTime) ? DateTime.Now : model.CreatedOnRange.End;

            predicate.And(p => p.CreatedOn >= model.CreatedOnRange.Start && p.CreatedOn <= endDate);
        }

        //Include status filtering if any filters are present
        if (model.StatusFilter != null && model.StatusFilter.Any())
        {
            //use Id and name to search for status
            predicate.And(p => model.StatusFilter.Any(f => f.StatusId == p.StatusId || p.Status == f.Name));
        }

        var pagination = model as PaginationModel;

        var sessions = Manager.FindSessions(predicate, pagination);

        return sessions;

问题是,我的Where子句没有被评估,所有结果都被返回。我还应该做些什么才能使Where语句正常工作?

1 个答案:

答案 0 :(得分:1)

您需要将predicate分配给自己。

 predicate = predicate.And(p => p.TenantId == model.TenantId.Value);