0

How to return the count of a 1 to many navigation property?

This doesn't work. (On client i get value 0).

The solution here is not bad:

[HttpGet]
public IQueryable<object> AccountsSummary()
{
    return from t in _contextProvider.Context.Accounts
        select
            new
            {
                t,
                ContactsCount = t.Contacts.Count()
            };
} 

But i think this will disable the odata capabilities to filter from client-side?

Thanks

Felix

Community
  • 1
  • 1
flieks
  • 175
  • 1
  • 3
  • 13
  • Do you want the total count of all contacts that have a parent account assigned, or do you want to find out how many contacts a single account has? – HotTowelie May 26 '16 at 15:23
  • I want the latter (the count of contacts per account) – flieks May 30 '16 at 11:51

1 Answers1

0

If you want the count of an objects 1:n navigational property you can use simple linq:

[HttpGet]
public int AccountContactCount(int accountId)
{
    return _contextProvider.Context.Accounts.Where(p => p.Id == accountId).Select(p => p.Contacts).Single().Count();
}

Add a nullcheck before this just in case you sent a non existing id or the account has no contacts, but this should work.

HotTowelie
  • 123
  • 8
  • Thanks, that's true but i don't want an extra request (then you need to code it client side + it's an extra request). With breeze i can get all navigation properties loaded (which would give the count) but for some navigation properties i just want the count, not the actual data.. – flieks Jun 01 '16 at 18:11