No need for the null coalesce.
var count = _db.cart.Count(c => c.UserId == id); // get record count
If you're actually trying to get a sum:
var total = _db.cart.Where(c => c.UserId == id)
.Select(c => (int?)c.Quantity)
.Sum() ?? 0; // get total
FYI, regarding the code you originally posted...
You wouldn't want to call ToList().Count()
, because calling ToList()
will execute your query and pull back data. You'll end pulling back a list of quantities and performing the count locally, instead of generating an SQL statement that simply performs the count and returns a single number.