0

I got a Problem with my API. I want to get a random amout of questions back.

The Model of my question has a list of answers and hints:

public class Question
{
    public int Id { get; set; }
    public string Text { get; set; }
    public string Explanation { get; set; }
    public Category Category { get; set; }
    public ICollection<Answer> Answers { get; set; }
    public ICollection<Hint> Hints { get; set; }
}

normally if i call my get method i get a json with all the lists back

return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).ToList();

 {
    "id": 1,
    "text": "Test?",
    "explanation": "Test",
    "category": null,
    "answers": [
        {
            "id": 1,
            "text": "Test",
            "isCorrect": true
        },
        {
            "id": 2,
            "text": "Test1",
            "isCorrect": false
        },
        {
            "id": 3,
            "text": "Test2",
            "isCorrect": false
        },
        {
            "id": 4,
            "text": "Test3",
            "isCorrect": false
        }
    ],
    "hints": [
        {
            "id": 1,
            "text": "..."
        },
        {
            "id": 2,
            "text": "..."
        }
    ]
}

But if I want to get random picks with a orderby i only got empty lists

return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).OrderBy(o => Guid.NewGuid()).Take(amount).ToList();

{
        "id": 1,
        "text": "test",
        "explanation": "..-",
        "category": null,
        "answers": [],
        "hints": []
    }

Does someone have a Idea to fix this?

MiroBehn
  • 13
  • 5
  • According to [this](https://stackoverflow.com/questions/9449452/linq-order-by-random) answer, you should be using a [Fisher-Yates Shuffle](https://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c-sharp/375446#375446) algorithm. – ikerbera Nov 23 '18 at 11:06

1 Answers1

0

After sql need to be a list. I got a similar problem a long time ago. Hope it s help, was with an older version of Ef.

So you have to add a ToList before the OrderBy.

return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).ToList().OrderBy(o => Guid.NewGuid()).Take(amount).ToList();

LeBigCat
  • 1,737
  • 1
  • 11
  • 16