Home > Net >  How to use Count in EF Repository?
How to use Count in EF Repository?

Time:12-13

I have small problem when I want to use Count() in Entity Framework ASP.NET MVC repository.

Here's my code:

 public ArrayDataVM CountAll()
 {
     return _db.ArrayDatas.Count();
 }

It's said cannot convert int to Model. This is the screenshot:

enter image description here

Because I want to call it in another controller like to tidy the code. Like this (this is just one of example because there are more long query) :

Before (direct to DbContext):

ViewBag.CountAll = _db.ArrayDatas.Count();

After (via repository):

ViewBag.CountAll = _adRepo.CountAll();

Thanks for your help :) .

CodePudding user response:

you can use this code: Inside Repository:

public async Task<int> CountAllAsync()
{
   return await _db.ArrayDatas.CountAsync();
}

After (via repository):

 ViewBag.CountAll =await _adRepo.CountAllAsync();

CodePudding user response:

If you use UnitOfWork pattern, you can return the inserted/updated/deleted row count with SaveChanges() method.

public int SaveChanges()
{
    var result = _context.SaveChanges();
    return result;
}
  • Related