Selecting a new type from linq query

后端 未结 2 382
醉话见心
醉话见心 2021-01-13 20:43

I\'m trying to transform some data selected out of a repository using Linq.

My code so far:

Repository _repository = new Repository<         


        
相关标签:
2条回答
  • 2021-01-13 20:56

    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();
    
    0 讨论(0)
  • 2021-01-13 21:05

    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();
    
    0 讨论(0)
提交回复
热议问题