我有一个旅游项目(ASP.NET MVC4)。我想在LINQ where子句中使用多个参数搜索Tours。
这是我的观点:
<form class="green" id="formsearchtravel" method="get" action="@Url.Content("~/" + "search")">
<div class="col-lg-3 col-sm-6">
<select name="destination" >
<option value="any">All </option>
<option value="India">Ấn độ</option>
<option value="thailand">Thailand</option>
<option value="japan">Nhật bản</option>
<option value="uk">Anh</option>
</select>
</div>
<div class="col-lg-3 col-sm-6">
<select name="duration" >
<option value="any">All</option>
<option value="5">from 0 - 5</option>
<option value="10">from 05 -10</option>
<option value="15">from 10 -15</option>
<option value="16">over 15 days</option>
</select>
</div>
<div class="col-lg-3 col-sm-6">
<select name="price" >
<option value="any">All</option>
<option value="500">A – 0 – 500 $</option>
<option value="1000">B – 500 – 1000 $</option>
<option value="2000">C – 1000 – 2000 $</option>
<option value="3000">D – 2000 – 3000 $</option>
<option value="4000">E – Trên 4000 $</option>
</select>
</div>
<div class="col-lg-3 col-sm-6">
<input value="Search" type="submit" />
</div>
</form>
这是控制器:
public IEnumerable<TourSummaryDto> GetSearchTours(string destination, int? duration, int? price)
{
var query = _tourItemRepository.GetAll();
return
ConvertToTourSummaryDtoQuery(
query.Where(p => p.Category.Name.ToUpper() == destination.ToUpper() && p.TourContent.Giagoc > 500 && p.TourContent.Soluongngay < 15).OrderByDescending(t => t.CreatedDate));
}
如何使用Destination = any
或Destination = something And Duration = all
或Duration = something AND Price = all or Price = somethings
如何搜索所有这些(目的地,持续时间和价格)
感谢任何帮助。
答案 0 :(得分:1)
您可以根据给定的输入建立where
子句。
例如:
public IEnumerable<TourSummaryDto> GetSearchTours(string destination, int? duration, int? price)
{
var query = _tourItemRepository.GetAll();
//always has a destination
query = query.Where(p => p.Category.Name.ToUpper() == destination.ToUpper();
//filter results that also have the given duration, only if a value is provided.
if (duration.HasValue)
{
query = query.Where(p => p.Duration == duration.Value);
}
return
ConvertToTourSummaryDtoQuery(query.OrderByDescending(t => t.CreatedDate));
}
这显然和条件在一起。如果你有一个OR条件(特别是限制为两个输入值),那么你需要将它们组合成一个where
子句。