简体   繁体   中英

Convert LinQ from SQL statement in C# MongoDB

I'm working on converting my project from MySQL to MongoDB. I'm converting a few statements to MongoDB by using LinQ.

Here is my Original Statement:

SELECT COUNT(machinelograwdata.Parameter1) AS 'HideSheetCounter', 
    machinelograwdata.Parameter42 AS 'Orders', 
    machinelograwdata.MachineID 
FROM machinelograwdata 
WHERE EventID = '14' 
    AND CONVERT( Parameter35 , DECIMAL) <> 0 
    AND machinelograwdata.StartTime <= ' strSearchingEndDate + ' 
    AND machinelograwdata.StartTime >= ' strSearchingStartDate + ' 
GROUP BY Parameter42 , machinelograwdata.MachineID

and I try the following LinQ syntax and I got error:

var Temp3 = from c in MachineCollection.AsQueryable()
        where c.StartTime >= DateTime.Parse(strSearchingStartDate)
              && c.StartTime <= DateTime.Parse(strSearchingEndDate)
              && c.EventID == "14"
              && c.Parameter35 != "0"
        group c by new { c.Parameter42, c.MachineID } into grps
        select new
        {
            MachineID = grps.Key.MachineID,
            Orders = grps.Key.Parameter42,
            HideSheetCounter = grps.Count(x => x.Parameter1)
        };

Visual Studio raises issues at select and x.Parameter1 For x.Parameter1 , the error is Cannot implicitly convert type 'string' to 'bool'
but my POCO is

[BsonElement("Parameter1")]
public string Parameter1
{
    get;
    set;
}

What is my code wrong? Could you give me some hints? Thank you

The Count() method needs a predicate which returns a boolean for each element you want to count satisfing that condition.

To mimic the same behavior of COUNT(columnName) you need to provide the method a predicate which excludes null values for your field:

grps.Count(x => x.Parameter1 != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM