C#EF随机顺序导致相关列表消失

时间:2018-11-23 10:54:53

标签: c# entity-framework repository

我的API出现问题。我想随机回答一些问题。

我的问题的模型列出了答案和提示:

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; }
}

通常,如果我调用get方法,则会得到一个json,其中包含所有列表

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": "..."
        }
    ]
}

但是,如果我想按订单顺序随机选择,我只会得到空列表

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": []
    }

有人有解决此问题的想法吗?

1 个答案:

答案 0 :(得分:0)

sql之后需要一个列表。我很久以前也遇到过类似的问题。 希望对旧版Ef有所帮助。

所以您必须在OrderBy之前添加一个ToList。

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