How to convert SQL query into LINQ?

2019-09-22 02:25发布

How can I convert the following SQL query into linq? This is what is tried

    SELECT COUNT(DISTINCT SampleDateTime) AS Total
    FROM dbo.PrecisionArchive
    WHERE AgencySourceId = 7 AND EventType IN('R', 'ONS')

2条回答
不美不萌又怎样
2楼-- · 2019-09-22 02:44

Something like this should work:

var result = 
    (from x in dbContext.PrecisionArchive
     where x.AgencySource == 7 &&
           (x.EventType == "R" || x.EventType == "ONS")
     select x.SampleDateTime)
    .Distinct()
    .Count();

You could also try using Contains to represent the IN clause, but I don't believe this is supported by 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();
查看更多
Melony?
3楼-- · 2019-09-22 02:46

You could use:

var total = dbo.PrecisionArchive.Where(p => p.AgencySourceId == 7)
                                .Where(p => p.EventType == "R" || p.EventType == "ONS")
                                .Select(p => p.SampleDateTime)
                                .Distinct()
                                .Count();
查看更多
登录 后发表回答