谓词生成器问题 [英] Predicate Builder Issue

查看:100
本文介绍了谓词生成器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有2个数据库表..1个表进行不同的运动:

Imagine I have 2 database tables.. 1 table holds different sports:

|ID|    |Sport|
 1       Baseball
 2       Basketball
 3       Soccer

第二个表包含Sports表的ID,因此是外键

The second table holds the ID of the Sports table, so a foreign key

表名-TestDB

|ID|    |SportsID|        |Test|
  1          1             test1
  2          3             test2
  3          2             test3
  4          1             test4
  5          2             test5

现在我正在使用Predicate Builder允许用户在我的Web应用程序中搜索表:

Now I am using Predicate Builder to allow the user to search through the table in my web application:

[HttpPost]
    public ActionResult allDailySummaries(int? sport, int? sport1)
    {
        List<TestDB> lstTDB = db.TDB.Include(x => x.Sports).ToList();

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

        if (!string.IsNullOrWhiteSpace(sport.ToString()))
        {
            predicate = predicate.And(x => x.SportsID == sport);   
        }

        if (!string.IsNullOrWhiteSpace(sport1.ToString()))
        {
            predicate = predicate.And(x => x.SportsID == sport).;
        }

        if (predicate.Parameters.Count > 0)
        {
            lstTDB = db.TestDB.AsExpandable().Where(predicate).ToList();
            ViewBag.countSports = lstTDB.Count();
            Session["Paging"] = lstTDB;
            ViewBag.Paging = lstTDB.ToPagedList(page ?? 1, 25);
            return View(lstTDB.ToPagedList(page ?? 1, 25));
        }
        else
        {
            return View(lstTDB.ToPagedList(page ?? 1,25));
        }

我应该能够按2个运动项目进行过滤或搜索..因此,如果我想按TestDB中的所有记录进行搜索,无论是棒球还是篮球,那就是我想要的..但​​是当我尝试此操作时,它什么都不会返回,但是如果我只搜索1种运动,它将起作用.

I should be able to filter or search by 2 sports.. so if I wanted to search by all records in the TestDB that are either baseball or basketball then that's what I want.. but when I try this, it returns nothing, but if i only search 1 sport it works.

感谢您的帮助.

推荐答案

我有解决方法:

List<int> lstSports = new List<int>();
        if(sport != null)
        {
            lstSports.Add(Convert.ToInt32(sport));
        }
        if (sport1 != null)
        {
            lstSports.Add(Convert.ToInt32(sport1));
        }
        if (lstSports.Count > 0)
        {
            foreach(int i in lstSports)
            {
                if(lstSports.IndexOf(i) == 0)
                {
                    predicate = predicate.And(x => x.SportsID == i);
                }
                else
                {
                    predicate = predicate.Or(x => x.SportsID == i);
                }
            }
        }

这篇关于谓词生成器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆