Search code examples
c#linqlinq-to-sqlsql-to-linq-conversion

How can i use Count with condition in LINQ


I wanted to get the number of times that , the customer participant our events. So the sql code is suppose to be like this.

SELECT COUNT(CustomerID)
FROM EventsParticipants
WHERE (CustomerID == Session["CustomerID"]);

And LINQ code is like this is I am not mistaken, it will return the value of the Count() right.

var recordcount = db.EventParticipants.Where(Session["CustomerID] == db.EventParticipants.CustomerID).Count();

But it return this error code

'DbSet<EventParticipants>' does not contain a definition for 'CustomerID' and no accessible extension method 'CustomerID' accepting a first argument of type 'DbSet<EventParticipants>' could be found (are you missing a using directive or an assembly reference?)    LeafLife

Solution

  • You need to pass a lambda that takes the entity and returns a bool, like this

    var id = Session["CustomerID"];
    var recordcount = db.EventParticipants.Where(x => x.CustomerID == id).Count();
    

    Note you'll also want to put the id into a separate variable as EF will not be able to translate Session into SQL.