我想知道是否可以使用Entity Framework
连接查询的结果。
请忽略联接查询是否有意义。我只是想解释我的问题,而不是进行正确的查询。为了清楚起见,我将其简化了很多:
var firstJoinQuery = (from company in this.TimesheetsContext.companies
join country in this.TimesheetsContext.Countries
on company.CountryId equals country.Id
where (country == 'USA')
select new { CountryId = country.Id }).Distinct();
var secondJoinQuery = (from country in this.TimesheetsContext.Countries
join firstJoinQuery
on country.CountryId equals firstJoinQuery.CountryId
select new { Country = country }).Distinct();
我发誓我以前做过,但是我无法在第二个或第三个中使用一次联接的结果。
我要这样做的原因是为了使事情更易于阅读,因为在使用EF和复杂查询时并不总是很明显。
我目前的变通方法是转向实际的存储过程,因为它肯定会更易于阅读,但如果可能的话,我想先在EF中试一试。
谢谢。
答案 0 :(得分:0)
您可以将两个查询与Union结合使用。
答案 1 :(得分:0)
我认为您可以做到,但是您需要在查询中使用.ToList()
,因为Distinct()
执行就像延期一样。在这里,您尝试像查询字符串这样的联接查询,而不是结果查询。
var firstJoinQuery = (from company in this.TimesheetsContext.companies
join country in this.TimesheetsContext.Countries
on company.CountryId equals country.Id
where (country == 'USA')
select new { CountryId = country.Id }).Distinct().ToList;
var secondJoinQuery = (from country in this.TimesheetsContext.Countries
join firstJoinQuery
on country.CountryId equals firstJoinQuery.CountryId
select new { Country = country }).Distinct().ToList();
var thirdJoinQuery .....
答案 2 :(得分:0)
我通过进一步研究终于弄清楚了。
我找到了以下文章:Combining LINQ Queries (or, When to Call ToList)有帮助。
要解决我的问题,我必须返回完整的对象,而不仅仅是返回一个属性,请删除.Distinct()和.ToList(),以便对此进行更改:
var firstJoinQuery = (from company in this.TimesheetsContext.companies
join country in this.TimesheetsContext.Countries
on company.CountryId equals country.Id
where (country == 'USA')
select new { CountryId = country.Id }).Distinct().ToList;
到
var firstJoinQuery = (from company in this.TimesheetsContext.companies
join country in this.TimesheetsContext.Countries
on company.CountryId equals country.Id
where (country == 'USA')
select company;
我还没有解决这个问题,也没有完成对完整链接的查询,但是如果我发现了,我将更新此答案。
希望这会有所帮助。