my problem is occurred when I tried to grouping data from two tables in this controller as below:
public class QuestionModelsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Quiz()
{
var Ans = from ansewrs in db.AnswerModels
join question in db.QuestionModels
on ansewrs.QuestionID equals question.ID
select ansewrs;
var grouped = from j in Ans
group j by j.Question.QuestionText
into gr
select new CheckListModel
{
QuestionText = gr.Key,
Questions = gr
};
return View(grouped.ToList());
}
My ViewModels are:
public class CheckListModel
{
public string QuestionText { get; set; }
public virtual IEnumerable<QuestionModel> Questions { get; set; }
}
public class QuestionModel
{
public int ID { set; get; }
public string QuestionText { set; get; }
public string SelectedAnswer { set; get; }
public virtual IList<AnswerModel> Answers { set; get; }
}
public class AnswerModel
{
public int ID { set; get; }
public string AnswerText { set; get; }
public int QuestionID { get; set; }
public virtual QuestionModel Question { get; set; }
}
This row Questions = gr
is not recognized , thus this error will occur:
Error CS0266 Cannot implicitly convert type 'System.Linq.IGrouping<string, MyAssembly.AnswerModel>' to 'System.Collections.Generic.IEnumerable<MyAssembly.QuestionModel>'
. An explicit conversion exists (are you missing a cast?)
Please help me and Thank you very much
Questions = gr.ToList()
, but you have a different type of source and destination collections,AnswerModel
andQuestionModel
. It makes sense to review the logic of your queriesQuestions = gr.Select(a => a.Question)
CheckListModel
is just a grouping ofQuestionModels
byQuestionText
. You could probably simplify the whole query by completely removing the join with theAnswerModels