In my UserRepository
I have a GetActive
method:
public IEnumerable<User> GetActive()
{
var users = context.Set<UserTbl>().Where(x => x.IsActive);
foreach(var user in users)
{
yield return entityMapper.CreateFrom(user);
}
}
The entityMapper
is used to map from an EF-generated UserTbl
to the User
domain entity.
There exists thousands of users so I want the GetActive
method to defer execution while returning the IEnumerable<User>
so that the entire list isn't pulled unnecessarily. I have done that above with the foreach
and yield
.
When testing, it seems that the all the data is being fetched regardless. The following two calls take the same time:
// Get only 5 users in memory
var someUsers = UserRepository.GetActive().Take(5).ToList();
// Get all 100,000 users into memory
var allUsers = UserRepository.GetActive().ToList();
What am I doing wrong?