Justin99b
Justin99b

Reputation: 103

Linq count returns 0 but foeach returns something else

Im currently programming a webinterface for gameservers in C# with Entity Framework and ASP-Net

and got following problem.

so this

string apikey = blablabla
userManager.Users.Count(u=> u.ApiKeys.Contains(apiKey) || u.SupportApiKey == apiKey))

should return 1 but returns 0

and this

bool found = false;
foreach (WebinterfaceUser u in userManager.Users)
    if (u.ApiKeys.Contains(apiKey) || u.SupportApiKey == apiKey)
        found = true;

return true (so essentially 1 because i have only one database entry)

so why is that?

it does not make sense to me because both functions should return the same result right?

im also kinda new to c# and maybe im missing something i hope you can help me :)

Upvotes: 0

Views: 137

Answers (2)

Justin99b
Justin99b

Reputation: 103

The Solution is as following

new WebinterfaceDbContext().Users.ToList().First(u => u.ApiKeys.Contains(apiKey));

after some investigation and testing i got this error:

'System.Collections.ObjectModel.Collection`1[System.Guid]' cannot be used for parameter of type 'System.L inq.IQueryable`1[System.Guid]'

so i simply added ToList() to Users and it worked :)

Upvotes: 0

Gabriel Llorico
Gabriel Llorico

Reputation: 1803

if memory is not an issue. try this.

var apiCounts = userManager.Users.ToList().Count(u=> u.ApiKeys.Contains(apiKey) || u.SupportApiKey == apiKey));

it will be executed on memory not on db, maybe something in db level vs server side is causing the error.

Upvotes: 1

Related Questions