I\'m trying to transform some data selected out of a repository using Linq.
My code so far:
Repository _repository = new Repository<
I would suspect that your issue is that the MongoDB driver doesn't know how to create a Discipline
object (or an anonymous object for that matter).
You need to move out of the the IQueryable<>
and into IEnumerable<>
to make this work.
Try this:
var disciplines =
_repository
.Query()
.ToArray()
.Select(d => new Discipline
{
DisciplineCode = d.DisciplineCode,
Name = d.DisciplineName
})
.Distinct()
.ToList();
The .ToArray()
is the magic here. Let me know if this works.
You still may have issues with the .Distinct()
call working on your custom type, so you may need to try this:
var disciplines =
_repository
.Query()
.ToArray()
.Select(d => new
{
d.DisciplineCode,
d.DisciplineName
})
.Distinct()
.Select(d => new Discipline
{
DisciplineCode = d.DisciplineCode,
Name = d.DisciplineName
})
.ToList();
Not sure why your first example does not run, it looks Ok, see related question here. Possibly it might be a bug in your db driver ?
You could try using GroupBy to achieve the same result:
var disciplines = _repository.Query()
.GroupBy(d => new Discipline
{
DisciplineCode = d.DisciplineCode,
Name = d.DisciplineName
}
)
.ToList();