Keith Barrows Keith Barrows - 1 month ago 14
C# Question

Entity Frameworks - ToList() and 0 Records

When expecting a recordset (>=1 record) how do you check for that 0 record situation?

For example:

RivWorks.Model.FeedStoreReadOnly store = new RivWorks.Model.FeedStoreReadOnly(AppSettings.FeedAutosEntities_connString, AppSettings.FeedAutosEntities_metadata, AppSettings.FeedAutosEntities_providerName);
RivWorks.Model.NegotiationAutos.Entities _dbFeed = store.ReadOnlyEntities();
var companyDetails = from a in _dbFeed.ClientClientMap where a.CompanyID == CompanyId select a;
return companyDetails.ToList();


When this returns it is erroring out on the ToList() because there are no records that satisfied the WHERE clause. So, what would be the correct way to check for 0 records and what would the recommended return be at that point?




Addition based off below answer:

if (companyDetails.Count() > 0)
return companyDetails.ToList();
else
{
List<RivWorks.Model.NegotiationAutos.ClientClientMap> ret = new List<RivWorks.Model.NegotiationAutos.ClientClientMap>();
ret.Add(companyDetails.FirstOrDefault());
return ret;
}


Have not tested yet but that (logically) would seem to work. Wondering if there is an easier way though.




NOTE:

I got it figured out. The account that SQL was running under was not granted the correct set of permissions by the DBA. We altered all the GRANT statements on the new tables/views and it is now working.

Am still not sure what the correct answer is though. I am leaning towards creating a blank (new) record and adding to the List so our guys receiving the List have something to display (for edit if nothing else)...

Answer

You do not need to check for empty before calling ToList. ToList works fine with a query which returns no records; it will just return an empty list. You can use your original code and everything will work fine, with or without data in the table.

Most grids and the like will also cope fine with an empty list; they'll typically display a blank row for the user to create the first record.