Search code examples
c#linqentity-frameworkwcfwcf-rest

returning total count of records


I am using WCF rest service and i want to return total record count just as we have inlinecount in webapi or breeze.

My method in WCF is

   [WebGet(UriTemplate = "GiveMeNamesOfStudents", ResponseFormat = WebMessageFormat.Json)]
    public List<MyDataClass> GiveMeNamesOfStudentsList()
    {
        var returnData = (from myentity in myEntityRepository.AsQueryable()
                          select new MyDataClass
                            {
                                Id = myentity.Id,
                                Name = myentity.Name
                            }).Skip(PageSize * PageNo).Take(PageSize).ToList();
        return returnData;
    }

How can i return total record count of my actual data together with data?


Solution

  • I suggest to return a DTO containing your list and the total count.

    You can add other informations like the page count for example but i will keep it simple here.

    First create your generic DTO so you can use it in other methods too.

     public class ListResult<T>
     {
         public List<T> Data { get; set; }
         public int TotalCount { get; set; }
         public int Page{ get; set; }
     }
    

    Now return the object

    [WebGet(UriTemplate = "GiveMeNamesOfStudents", ResponseFormat = WebMessageFormat.Json)]
    public ListResult<MyDataClass> GiveMeNamesOfStudentsList()
    {
        var returnData = (from myentity in myEntityRepository.AsQueryable()
                          select new MyDataClass
                            {
                                Id = myentity.Id,
                                Name = myentity.Name
                            }).Skip(PageSize * PageNo).Take(PageSize).ToList();
    
        return new ListResult<MyDataClass> 
                            { 
                                 Data = returnData, 
                                 TotalCount = myEntityRepository.Count(), 
                                 Page = PageNo 
                            };
    }