我正在学习 MVC,我正在存储用户的出生日期以显示他的年龄。数据已正确保存。然后按照本教程对数据进行排序。它适用于名字和姓氏,但在按年龄排序时会抛出异常
LINQ to Entities 仅支持无参数构造函数和初始化程序。
我的行动准则是
public ActionResult Index(string sortOrder, int? page, string currentFilter, string q)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.FNSortParam = string.IsNullOrWhiteSpace(sortOrder) ? "FName_Desc" : "";
ViewBag.LNSortParam = sortOrder == "LName" ? "LN_Desc" : "LName";
ViewBag.AgeSortParam = sortOrder == "Age" ? "Age_Desc" : "Age";
var query = q;
if (query != null)
page = 1;
else
query = currentFilter;
var users = db.MyAppUsers.Select(a => a);
if (!string.IsNullOrWhiteSpace(query))
{
var nQuery = query.ToUpper();
users = users.Where(a => a.FName.ToUpper().Contains(nQuery) ||
a.LName.ToUpper().Contains(nQuery) || a.Email.Contains(nQuery));
}
switch (sortOrder)
{
case "FName_Desc":
users = users.OrderByDescending(a => a.FName);
break;
case "LName":
users = users.OrderBy(a => a.LName);
break;
case "LN_Desc":
users = users.OrderByDescending(a => a.LName);
break;
case "Age":
users = users.OrderBy(a => new DateTime(DateTime.Now.Subtract(a.DOB).Ticks));
break;
case "Age_Desc":
users = users.OrderByDescending(a => new DateTime(DateTime.Now.Subtract(a.DOB).Ticks));
break;
default:
users = users.OrderBy(a => a.FName);
break;
}
// public DateTime Age
//{
// get { return new DateTime(DateTime.UtcNow.Subtract(DOB).Ticks); }
//}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(users.ToPagedList(pageNumber, pageSize));
}
而对于视图是
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.FName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LName)
</td>
<td>
@{
var age = new DateTime(DateTime.UtcNow.Subtract(item.DOB).Ticks);
@Html.DisplayTextFor(modelItem => age.Year)
}
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
</tr>
}
我想不通。有人可以帮忙吗?