无法将类型隐式转换为System.Collections.Generic.List

时间:2016-01-29 17:25:24

标签: c# .net asp.net-mvc

我正在尝试对某些数据进行硬编码以进行测试,但似乎无法使其正常工作。我确信我错过了一些简单的事情。

这是我的代码:

0001-01-01 00:00:00 +0000 UTC

以下是我的模特:

public async Task<ActionResult> GetClusterAnswers(int clusterId, int sectionId)
{
    contractorId = UserInfo.targetCompanyID;
    var questions = await CommonClient.GetGeneralQandAsBySection(sectionId, contractorId);
    var selectedQuestion = questions.FirstOrDefault(q => q.QuestionClusterID == clusterId);
    int? questionid = selectedQuestion.QuestionID;

    QuestionsWithPairedAnswers question = new QuestionsWithPairedAnswers();
    question.QuestionID = questionid;
    question.vchQuestionText = selectedQuestion.vchQuestionText;
    question.vchTextElementOneHeader = selectedQuestion.vchTextElementOneHeader;
    question.vchTextElementTwoHeader = selectedQuestion.vchTextElementTwoHeader;

    question.Answers = new PairedAnswerTypes()
    {
        QuestionID = question.QuestionID,
        PairedTextElementAnswerID = 1,
        ContractorID = contractorId,
        vchTextElementOne = "ABC",
        vchTextElementTwo = "School Teachers"
    };
    return Json(question, JsonRequestBehavior.AllowGet);
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

问题出在这一行:

question.Answers = new PairedAnswerTypes()
        {
            QuestionID = question.QuestionID,
            PairedTextElementAnswerID = 1,
            ContractorID = contractorId,
            vchTextElementOne = "ABC",
            vchTextElementTwo = "School Teachers"

        };

问题。答案是List的{​​{1}},您为其分配了一个PairedAnswerTypes,您可以将此分配更改为列表初始化和分配:

PairedAnswerTypes

答案 1 :(得分:0)

Answers内的

QuestionsWithPairedAnswers属性为List<PairedAnswerTypes>,但在以下行中:

question.Answers = new PairedAnswerTypes()

您尝试将其设置为PairedAnswerTypes

将其更改为:

question.Answers = new List<PairedAnswerTypes>
{
    new PairedAnswerTypes()
    {
        QuestionID = question.QuestionID,
        PairedTextElementAnswerID = 1,
        ContractorID = contractorId,
        vchTextElementOne = "ABC",
        vchTextElementTwo = "School Teachers"
    }
}

这样您就可以根据媒体资源的要求将新答案 放入新的List