[英]How to create Linq2Sql query that will group records from linked table and calculate 2 count fields
在這里,我發現了如何使用Linq2Sql聯接表並計算鏈接記錄LINQ的數量-左聯接,分組依據和計數
我已經實現了它,對我來說效果很好:以下表達式
var v = from c in db.GetTable<Country>()
join t0 in db.GetTable<Team>() on c.Id equals t0.CountryId into t1
from team in t1.DefaultIfEmpty()
group team by c.Id into teamsGrouped
select new CountryTeamsInfo
{
CountryId = teamsGrouped.Key,
TeamsTotal = teamsGrouped.Count(),
// TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId==0)
}
;
List<CountryTeamsInfo> res = v.ToList();
生成以下查詢:
SELECT c.Id, Count(*) as c1
FROM countries c
LEFT JOIN teams t1 ON c.Id = t1.Country
GROUP BY c.Id
實際上,我還需要計算OwnerId字段不等於0的那些鏈接記錄。
看來我應該在linq表達式中取消注釋該行(TeamsWithoutOwnerFree = teamsGrouped.Count(t => t.OwnerId == 0)),但這不起作用,嘗試執行會導致錯誤:
給定的鍵在字典中不存在
該查詢不會進入SQL日志文件,並且我無法在調試器中對其進行檢查。
什么是從“團隊”表計算符合附加條件的行的正確方法?
PS,如果有關系,我使用C#4.0,MySql 5.1和BLToolkit 4.1
也許嘗試使用GroupJoin()
進行查詢:
var result = db.GetTable<Country>()
.GroupJoin(db.GetTable<Team>(),
c => c.Id,
t => t.CountryId,
(country, teams) => new
{
CountryId = country.Id,
TeamsTotal = teams.Count(),
TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId == 0)
})
.ToList();
由於RePierre的幫助,我得以找到正確的查詢:
var v = db.GetTable<Country>().Where(country => country.Allowed)
.GroupJoin(
db.GetTable<Team>(),
country => country.Id,
team => team.CountryId,
(country, teams) => new CountryTeamsInfo
{
CountryId = country.Id,
TeamsTotal = teams.Count(),
TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId != 0),
}
).GroupJoin(
db.GetTable<Team>().Where(te=>te.OwnerId==0),
cti => cti.CountryId,
team => team.CountryId,
(cti, teams) => new CountryTeamsInfo
{
CountryId = cti.CountryId,
TeamsTotal = cti.TeamsTotal,
TeamsWithoutOwnerFree = teams.Count(t => t.OwnerId != 0),
}
)
;
我擔心的是它使用2個子查詢...將嘗試對其進行優化。 任何想法都很棒
PS實際上,生成的SQL查詢看起來也很丑陋:
SELECT
cti.Id as Id1,
cti.c1 as c11,
(
SELECT
Count(*)
FROM
teams te
WHERE
cti.Id = te.Country AND te.User = 0
) as c2
FROM
(
SELECT
country.Id,
(
SELECT
Count(*)
FROM
teams t1
WHERE
country.Id = t1.Country
) as c1
FROM
countries country
WHERE
country.allow
這是在我的環境中有效的查詢:
from c in db.GetTable<Country>()
where c.Allowed
select new CountryTeamsInfo
{
CountryId = c.Id,
TeamsTotal = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed),
TeamsHasOwner = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed && t.OwnerId != 0),
}
不是最好的解決方案(我需要重復團隊選擇標准t。在每個子查詢中都允許),但是仍然可以很好地工作,並且生成的SQL很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.