我有很多国家,每个国家我都有很多球队。
团队控制器中的GetTeam端点检索单个Team及其相关的Nation。通过LINQ,查询是这样的:
Context.Teams.Include(t => t.Nation).First(t => t.Id.Equals(__id))
生成的JSON是我想要的:
{"team":{"name":"Team1","nation":{"id":1,"name":"Nation1"}}
现在让我们删除Team和Nation模型中的“名称”属性,并使用Translation创建新的模型关系。
我现在想要的是检索相同的JSON,但根据区域性使用不同的查询。 发疯了,了解我如何通过包含来实现它。
如何在LINQ中编写此查询?
select *
from Teams inner join
Translations TeamTr on Teams.id = TeamTr .id and TeamTr .culture = "IT" inner join
Nations on Teams.nation_id = Nations.id inner join
Translations NationTr on Nations .id = NationTr .id and NationTr .culture = "IT"
然后将结果数据构成为上面的JSON?
答案 0 :(得分:1)
例如:
(from team in Context.Teams
join teamTr in Context.Translations on team.id equals teamTr.id
join nation in Context.Nations on team.nation_id equals nations.id
join nationTr in Context.Translations on nation.id equals nationTr.id
where teamTr.culture == "IT" && nationTr.culture == "IT"
select new
{
teamName = team.name,
nationName = nation.name
}).ToList();
答案 1 :(得分:1)
很好抓tdayi。
首先,我创建了一个新类,它将作为linq结果的容器:
public class TeamDetailLinqDto
{
public Team Team { get; set; }
public Translation TeamTranslation { get; set; }
public Nation Nation { get; set; }
public Translation NationTranslation { get; set; }
}
这是linq查询:
public IQueryable<TeamDetailLinqDto> GetTeams()
{
var result = from team in Context.Teams
join teamTranslation in Context.Translations on
new { Id = team.Id, Locale = "IT" }
equals new { Id = teamTranslation.EntityId, Locale = teamTranslation.Locale }
join nation in Context.Nations on team.NationId equals nation.Id
join nationTranslation in Context.Translations on
new { Id = nation.Id, Locale = "IT" }
equals new { Id = nationTranslation.EntityId, Locale = nationTranslation.Locale }
select new TeamDetailLinqDto
{
Team = team,
TeamTranslation = teamTranslation,
Nation = nation,
NationTranslation = nationTranslation
};
return result;
}