我遵循了 MSDN 教程 ASP.NET 有关 MVC Web 应用程序> http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application 中的筛选功能
不幸的是,我无法选择具有枚举属性的对象。
使用的模型是:
public Bus()
{
public int BusID { get; set; }
public string RegNum { get; set; }
public Status? Status { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
其中枚举类型为:
public enum Status
{
ON, OFF
}
根据上述教程,我在总线控制器中实现了排序方法,如下所示:
public ViewResult Index(string searchString)
{
var buses = from b in db.Buses select b;
if (!String.IsNullOrEmpty(searchString))
{
buses = buses.Where(b =>
b.RegNum.ToUpper().Contains(searchString.ToUpper())
);
}
return View(buses.ToList());
}
它适用于 RegNum 过滤,但我无法通过搜索字符串值为给定状态选择总线。
b.Status.Equals(searchstring) 不起作用。
我将不胜感激任何提示
因为Status
不是string
。您可能希望将searchString
转换为Status
Status searchStatus = Enum.Parse(typeof(Status), searchString.ToUpper());
首先在查询中使用它(注意:不要将解析代码直接放入查询中)。或者Enum.TryParse
以避免潜在的异常。另请注意,保存在数据库中的内容是 int,0 表示 ON 和 1 表示 OFF。
请尝试以下更改:
public class Bus
{
public int BusID { get; set; }
public string RegNum { get; set; }
public Status Status { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
将状态作为第二个参数并筛选这两个参数。下面的示例代码。
public static IEnumerable<Bus> FilterBuses(string searchString, Status status)
{
//Setup some dummy data
var buses = new List<Bus>()
{
new Bus() { BusID = 12, RegNum = "Twelve", Status = Status.ON},
new Bus() { BusID = 13, RegNum = "Thirteen", Status = Status.OFF},
new Bus() { BusID = 20, RegNum = "Twenty", Status = Status.OFF}
};
IEnumerable<Bus> filteredList = new List<Bus>();
if (!String.IsNullOrEmpty(searchString))
{
filteredList = buses.Where<Bus>(b =>
b.RegNum.ToUpper().Contains(searchString.ToUpper()) &&
b.Status == status);
}
return filteredList.ToList();
}
然后,您可以按如下方式调用该方法:
// Expect only Twelve bus
var result = LinqTestMethod.FilterBuses("Twelve", Status.ON);
// Expect no buses
result = LinqTestMethod.FilterBuses("Twelve", Status.OFF);
// Expect 2 buses -- Twelve and Twenty
result = LinqTestMethod.FilterBuses("T", Status.OFF);