/// <summary> /// 根据用户编号和是否已读标识获取该用户下的所有已读列表或未读列表 /// </summary> /// <param name="userId">用户编号</param> /// <param name="isHasRead">bool,是否已读</param> /// <returns>已读或未读的实体对象列表</returns> public List<User_Policy> GetList(string userId, bool isHasRead) { List<User_Policy> userPolicyList = new List<User_Policy>(); IQueryable<User_Policy> userPolicys = null; if (isHasRead) { // 已读列表 userPolicys = (from userPolicy in _entityLibrary.User_Policy where userPolicy.UserId == userId && userPolicy.IsReaded == true group userPolicy by userPolicy.PolicyId into g select new User_Policy { UserId = userId, PolicyId = g.Select(userPolicy => userPolicy.PolicyId).First<Guid?>(), FirstReadDate = g.Min(userPolicy => userPolicy.FirstReadDate), LastReadDate = g.Max(userPolicy => userPolicy.FirstReadDate), IsReaded = isHasRead }); } else { // 已读列表 userPolicys = from userPolicy in _entityLibrary.User_Policy where userPolicy.UserId == userId && userPolicy.IsReaded == true group userPolicy by userPolicy.PolicyId into g select new User_Policy { UserId = userId, PolicyId = g.Select(userPolicy => userPolicy.PolicyId).First<Guid?>(), FirstReadDate = g.Min(userPolicy => userPolicy.FirstReadDate), LastReadDate = g.Max(userPolicy => userPolicy.FirstReadDate), IsReaded = isHasRead }; } foreach (User_Policy userPolicy in userPolicys) { userPolicyList.Add(userPolicy); } return userPolicyList; }
这样会报错,如下:
我想知道这是为什么吗?被搞得很纠结,求解!
错误提示很明白了,linq to ef 不支持用 select new 创建匿名类型,虽然 User_Policy 是实体类,但你的查询只返回部分的列,这是不允许,解决方法,先查询出符合条件的 User_Policy,再用 group by select new 等 创建匿名类型
173844862.Net高级部落
如果使用group by语句,则不需要select。这是之前学习时写的小例子http://www.cnblogs.com/QLJ1314/archive/2012/08/04/Linq.html 希望对你有所帮助吧
linq to EF 支持创建匿名, 你的 User_Policy 不是匿名又不是DbContext映射类型。
你可以ToList之后再转换。