【问题标题】:Sort sql data using joined dictionary使用连接字典对 sql 数据进行排序
【发布时间】:2015-08-25 13:28:39
【问题描述】:

在 SQL Server 2014 中,我有一个表 People,其中有一列 Country (int not null)。我想按Country 对行进行排序,但国家是一个整数,我想按国家名称排序。我在 db 中没有 Contries 表。

var countryDict = new Dictionary<int, string>();
countryDict.Add((int)ECountry.AT, "Austria");
countryDict.Add((int)ECountry.IT, "Włochy");
.......

IQueryable<PeopleModel> result = _entity.People.Where(...)

现在我想用带有国家 ID 和国家名称的字典加入我的 DbSet

// there exception occurs
var resultWithCountryName = result
    .Join(
         countryDict,
         p => (int)p.Country,
         c => c.Key,
         (p, c) => new { p, CountryName = c.Value })
    .ToList();

result = resultWithCountryName
    .OrderByDescending(p => p.Kraj)
    .Select(p => p.p)
    .AsQueryable();

毕竟我需要分页,所以我使用这个代码。

        var resultList = result
            .Include(p => p.OtherTable) // nevermind
            .Skip(searchCriteria.Offset)
            .Take(searchCriteria.RowsOnPage)
            .ToList();

当我执行 join 语句时出现异常

无法创建类型的常量值 'System.Collections.Generic.KeyValuePair`2[[System.Int32, mscorlib, 版本=4.0.0.0,文化=中性, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, 版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089]]'。 仅支持原始类型或枚举类型 上下文。

我的问题是

  1. 为什么会出现此错误?

  2. 也许我对这个问题的解决方案是错误的?

【问题讨论】:

  • 基本上 EF 不知道如何将 KeyValuePair 转换为 SQL 代码。您可以在Join 之前使用AsEnumerable,但这将为result 运行SQL,并且Join 将在内存中而不是在数据库中完成。
  • Countries 表添加到您的数据库中,并在您的People 表和新的Countries 表之间建立外键关系——迄今为止最简单、最可靠的解决方案......跨度>

标签: c# .net sql-server linq entity-framework


【解决方案1】:

可能将 .ToList()/AsEnumerable()/AsQueryable() 放在 People 查询的末尾。

IQueryable<PeopleModel> result = _entity.People.Where(...).ToList(); 

【讨论】:

  • 它不起作用,如果我删除转换为列表,当我尝试获取数据时会发生这种情况
  • @Jacek 当你给 .tolist() 时你得到了什么例外?
  • 同理:“无法创建类型的常量值”
  • 我相信罪魁祸首是 IQueryable 确保两边的数据类型相同。
猜你喜欢
  • 2014-10-23
  • 2019-09-24
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 2014-05-26
  • 2011-12-11
  • 1970-01-01
相关资源
最近更新 更多