【发布时间】:2017-02-28 17:17:45
【问题描述】:
以下查询在第二个选择查询中返回重复的结果。
国家/地区与联赛有0..1 to * 关系。
Leagues 与 userLeagues 有1 to * 关系。
return from ul in userLeagues
select new Map.Country
{
id = ul.Country.CountryId,
name = ul.Country.Common_Name,
leagues = userLeagues.Where(x => x.CountryId.Value == ul.CountryId.Value)
.Select(x => new Map.League
{
id = x.LeagueID,
name = x.leagueNameEN,
})
};
我尝试使用Distinct,但没有成功。
看来我必须使用 distinct 或 groupby countryId
输出如
[
{
"id": 1,
"name": "Europe",
"leagues": [
{
"id": 2,
"name": "Champions League",
},
{
"id": 3,
"name": "Europa league",
}
]
},
{
"id": 1,
"name": "Europe",
"leagues": [
{
"id": 2,
"name": "Champions League",
},
{
"id": 3,
"name": "Europa league",
}
]
}
]
【问题讨论】:
-
也许尝试在您分配给
leagues的查询末尾添加.ToList()。但是你所说的“重复”是什么意思?你是说每个国家都有所有的用户联盟,还是每个国家都有属于最后一个国家的所有用户联盟,还是什么? -
在哪些列/属性上重复?
-
你不能使用 group by 来删除重复的结果吗?
-
@Neel 这似乎是我的大问题。我试过了,但是......
-
看来您只需将
userLeagues与Country分组即可。或者从 Country 表开始并使用导航属性或GroupJoin和UserLeagues。一般来说,当您有 EF 相关问题时,您应该提供实体模型类。
标签: c# entity-framework linq