问题
Imagine I have 2 database tables.. 1 table holds different sports:
|ID| |Sport|
1 Baseball
2 Basketball
3 Soccer
The second table holds the ID
of the Sports table, so a foreign key
Name of Table - TestDB
|ID| |SportsID| |Test|
1 1 test1
2 3 test2
3 2 test3
4 1 test4
5 2 test5
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));
}
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.
Any help is appreciated.
回答1:
I have solution:
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);
}
}
}
来源:https://stackoverflow.com/questions/36624630/predicate-builder-issue