Вопрос

Struggling to get my count correct. I believe I am close but I need it to return 0 if there are no records in the database. The compiler doesnt like what I have now. Any help would be appreciated. Thanks

var count = (_db.cart.Where(c => c.UserId == id)
            .Select(c => (int) c.Quantity)).ToList().Count() ?? 0;
Это было полезно?

Решение 2

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.

Другие советы

You want to use Sum, not Count

var totalQuantity = _db.cart.Where(c => c.UserId == id)
                            .Select(c => c.Quantity)
                            .DefaultIfEmpty(0)
                            .Sum();

try this

var count=_db.cart.where(c=>c.Userid==id).Count();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top