如何将以下 SQL 查询转换为 linq?这是尝试过的
SELECT COUNT(DISTINCT SampleDateTime) AS Total
FROM dbo.PrecisionArchive
WHERE AgencySourceId = 7 AND EventType IN('R', 'ONS')
如何将以下 SQL 查询转换为 linq?这是尝试过的
SELECT COUNT(DISTINCT SampleDateTime) AS Total
FROM dbo.PrecisionArchive
WHERE AgencySourceId = 7 AND EventType IN('R', 'ONS')
你可以使用:
var total = dbo.PrecisionArchive.Where(p => p.AgencySourceId == 7)
.Where(p => p.EventType == "R" || p.EventType == "ONS")
.Select(p => p.SampleDateTime)
.Distinct()
.Count();
像这样的东西应该工作:
var result =
(from x in dbContext.PrecisionArchive
where x.AgencySource == 7 &&
(x.EventType == "R" || x.EventType == "ONS")
select x.SampleDateTime)
.Distinct()
.Count();
您也可以尝试使用Contains
来表示IN
子句,但我不相信 Linq-to-SQL 支持:
var result =
(from x in dbContext.PrecisionArchive
where x.AgencySource == 7 &&
new[] { "R", "ONS" }.Contains(x.EventType)
select x.SampleDateTime)
.Distinct()
.Count();