事件源头:
当用IQueryable查询并用groupby select 时,每次都new object匿名对象,导致在var mEntitys = projectApp.SearchDataAllYear();
时mEntitys中data["main"]不可遍历
public Result SearchDataAllYear()
{
Dictionary<string, List<ProjectDetailEntityExt>> mEntitys = new Dictionary<string, List<ProjectDetailEntityExt>>();
List<ProjectEntity> mProjectItems = new List<ProjectEntity>();
var mainlist = detailviewService.IQueryable().Where(p => p.F_DeleteMark == null || p.F_DeleteMark == false)
.GroupBy(p => new { p.F_FullName, p.F_ProjectYear })
.Select(p => new
{
p.Key.F_FullName,
p.Key.F_ProjectYear,
total = p.Sum(w => w.F_ProjectFee)
}).ToList();
Result rs = new Result();
rs.data.Add("main", mainlist);
return rs;
}
解决方法:定义一个实体类,替代匿名object
//新建实体类
public class mp
{
public string project_id { get; set; }
public string projectTitle { get; set; }
public string projectFullName { get; set; }
public int projectYear { get; set; }
public DateTime? projectTime { get; set; }
public Decimal? total { get; set; }
}
//改用实体类
public Result SearchDataAllYear2()
{
Dictionary<string, List<ProjectDetailEntityExt>> mEntitys = new Dictionary<string, List<ProjectDetailEntityExt>>();
List<ProjectEntity> mProjectItems = new List<ProjectEntity>();
var sonlist = detailviewService.IQueryable().Where(p => p.F_DeleteMark == null || p.F_DeleteMark == false)
.GroupBy(p => new { p.project_id,p.F_ProjectTitle,p.F_FullName,p.F_ProjectYear,p.F_ProjectTime })
.Select(p => new mp()
{
project_id = p.Key.project_id,
projectTitle = p.Key.F_ProjectTitle,
projectFullName = p.Key.F_FullName,
projectYear = p.Key.F_ProjectYear,
projectTime = p.Key.F_ProjectTime,
total = p.Sum(w => w.F_ProjectFee)
}).ToList();
Result rs = new Result();
rs.data.Add("son", sonlist);
return rs;
}
此时可以遍历,注意要用IQueryable<T>
强制类型转换一下
var me = projectApp.SearchDataAllYear2();
foreach (var attt in (IQueryable<ProjectApp.mp>)me.data["son"])
{
var pid = item.project_id;
var projectTitle = item.projectTitle;
var projectFullName = item.projectFullName;
var projectYear = item.projectYear;
var projectTime = item.projectTime;
var total = item.total;
}