EF错误无法创建“匿名类型”类型的常量值。在此上下文中仅支持基元类型或枚举类型

时间:2015-05-25 12:19:31

标签: c# .net entity-framework

我查询了一些集合,然后将我的结果转换为JSON,但得到了以下错误:

  

无法创建“匿名类型”类型的常量值。只要   在此上下文中支持原始类型或枚举类型

以下是我的代码,请指导&帮助我。

  var AllStatus = RepositoryFactory.OrderStatusRepository.GetAll().AsEnumerable().Select(s => new
            {
              Status =  s.Status,
               StatusId= s.Id
            });

            var AllUsers = RepositoryFactory.UserRepository.GetAll().AsEnumerable().Select(u => new
            {
                UserId= u.UserId,UserName=u.UserName 
            });

            var result = RepositoryFactory.OrderHistoryRepository.GetAll().Select(v => new
            {
                PatientId = v.UserId ,
                UserName = AllUsers.Where(u=>u.UserId==v.UserId).Select(u=>u.UserName),
                Status = AllStatus.Where(s=>s.StatusId==v.OrderStatusId).Select(s=>s.Status),
                StatusDate = v.UpdatedDate,
                Amount = v.Amount  
            }) ; 


            returnModel.Data = result.ToJSON();

感谢

1 个答案:

答案 0 :(得分:0)

  1. 部分代码:AllUsers.Where(u=>u.UserId==v.UserId).Select(u=>u.UserName)AllStatus.Where(s=>s.StatusId==v.OrderStatusId).Select(s=>s.Status)返回IEnumerable<string>,我猜您需要单string;
  2. 取而代之的是Select方法,请使用ToDictionary
  3. var AllStatus = RepositoryFactory.OrderStatusRepository.GetAll().AsEnumerable()
                   .ToDictionary(x=> x.Id, x=> x.Status);
    
    var AllUsers = RepositoryFactory.UserRepository.GetAll().AsEnumerable()
                  .ToDictionary(u => u.UserId, u=> u.UserName);
    
    var result = RepositoryFactory.OrderHistoryRepository.GetAll()
            .Select(v => new
            {
                PatientId = v.UserId ,
                UserName = AllUsers.ContainsKey(v.UserId) ? AllUsers[v.UserId] : null,
                Status = AllStatus.ContainsKey(v.StatusId) ? AllUsers[v.StatusId] : null,
                StatusDate = v.UpdatedDate,
                Amount = v.Amount  
            }) ;