I have a DbSet<T>
that I need to project onto a different type. For the projection, I use Select
.
If I call directly Select
on my DbSet<T>
like:
private IEnumerable<PersonPOCO> _getPersons(ILocator loc)
{
using(var service = loc.GetService())
{
return service.GetPersons().Select(p => Mapper.ToPoco(p));
}
}
This will throw a NotSupportedException
because Select
is not recognized by entity framework (which is kinda obvious).
So I'll need to "concretize" the list by calling ToList()
:
private IEnumerable<PersonPOCO> _getPersons(ILocator loc)
{
using(var service = loc.GetService())
{
return service.GetPersons()
.ToList()
.Select(p => Mapper.ToPoco(p));
}
}
If I leave it like this, Select
being 'lazy' will only be evaluated when the list is really enumerated. But by that time, the Context used by the service will have been disposed (outside of the using
statement) so I will have a DbContextDisposedException
.
So I need to directly enumerate the list inside the using
private IEnumerable<PersonPOCO> _getPersons(ILocator loc)
{
using(var prov = loc.GetService())
{
return prov.GetPersons()
.ToList()
.Select(p => Mapper.ToPOCO(p))
.ToList();
}
}
Is there no way I can avoid calling ToList()
twice in the same instruction?