以下
linq to entities查询给出以下结果:
public class UserCountResult { public DateTime? date { get; set; } // **should this be string instead?** public int users { get; set; } public int visits { get; set; } } public JsonResult getActiveUserCount2(string from = "",string to = "") { var query = from s in db.UserActions group s by EntityFunctions.TruncateTime(s.Date) into g select new UserCountResult { date = g.Key,// can't use .toString("dd.MM.yyyy") here users = g.Select(x => x.User).Distinct().Count(),visits = g.Where(x => x.Category == "online").Select(x => x.Category).Count() }; return Json(query,JsonRequestBehavior.AllowGet); }
结果:
[{"date":"\/Date(1383433200000)\/","users":21,"visits":47},{"date":"\/Date(1383519600000)\/","users":91,"visits":236}]
而不是像/ Date(1383433200000)/这样的东西,我需要格式为“dd.MM.yyyy”的日期,例如
[{"date":"29.11.2013",{"date":"30.11.2013","visits":236}]
我找不到如何更改查询中的格式,我不知道该怎么做..我甚至不明白为什么g.Key是可以为空的…感谢您的任何输入!
解决方法
g.Key可以为空,因为它是EntityFunctions.TruncateTime的签名.
http://msdn.microsoft.com/en-us/library/dd395596.aspx.
要从Linq退出到实体,您可以保持查询不变,并在事实之后将其投影:
return Json(query.AsEnumerable().Select(r => new { date = r.date.GetValueOrDefault().ToString("dd.MM.yyyy"),users = r.users,visits = r.visits }),JsonRequestBehavior.AllowGet);
它不漂亮,但这是Linq to Entities for you.