问题
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?
回答1:
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
};
}
回答2:
You have to do query the DB twice; once without .Skip.Take
, to get the total count, then run the same query again with .Skip.Take
to get the page of data.
var returnData = (from myentity in myEntityRepository.AsQueryable()
select new MyDataClass
{
Id = myentity.Id,
Name = myentity.Name
}).Skip(PageSize * PageNo).Take(PageSize).ToList();
var totalCount = myEntityRepository.myentity.count();
Another alternative may be to not use EF, and instead just call a stored procedure that could run both queries and return both values in output parameters. This would still run 2 queries, but would only use 1 call frm your app to the DB instead of 2.
回答3:
Because your method's return type is List<MyDataClass>
, you can't return anything else. You'll need to introduce a DTO that returns your entities along with the count:
public class MyDataClassDTO
{
public List<MyDataClass> Data { get; set; }
public int TotalRecordCount { get; set; }
}
And return that.
来源:https://stackoverflow.com/questions/26779263/returning-total-count-of-records