【发布时间】: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]]'。 仅支持原始类型或枚举类型 上下文。
我的问题是
为什么会出现此错误?
也许我对这个问题的解决方案是错误的?
【问题讨论】:
-
基本上 EF 不知道如何将
KeyValuePair转换为 SQL 代码。您可以在Join之前使用AsEnumerable,但这将为result运行SQL,并且Join将在内存中而不是在数据库中完成。 -
将
Countries表添加到您的数据库中,并在您的People表和新的Countries表之间建立外键关系——迄今为止最简单、最可靠的解决方案......跨度>
标签: c# .net sql-server linq entity-framework