【问题标题】:EF error Unable to create a constant value of type 'Anonymous type'. Only primitive types or enumeration types are supported in this contextEF 错误无法创建“匿名类型”类型的常量值。此上下文仅支持原始类型或枚举类型
【发布时间】:2015-05-25 12:19:31
【问题描述】:

我正在查询一些集合,然后将结果转换为 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();

谢谢

【问题讨论】:

  • 确保您的查询中没有计算属性(例如 s.Status)。

标签: c# .net entity-framework


【解决方案1】:
  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
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  
        }) ;

【讨论】:

  • 对不起,因为我不知道好的 lambda 所以无法修复它。我试过你的代码,最后一次选择有 4 个错误,其中 'u.' .错误消息是“名称 'u' 在当前上下文中不存在”。在用户名和状态中,我需要选择文本而不是 id。你能帮忙吗?非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多