While working on a problem I realized I need to get query where the data from Table "questions" is reliant on count of Primary key "questions.Id" in another table "Upvotes" where "questionId" is a foreign key to "questions.Id" and can have multiple entries.
So how my system works is I add entries of upvotes to upvote table and I can simply count(particular question id) and total number of questions.
I am stuck with figuring out how to get list of all questions and their respective upvotes.
Example Question Table:
id(pk) question
1 "first quues"
2 "second ques"
3 "third ques"
Example Upvote table:
id(pk) questionid userid(user who upvoted)
1 2 "alpha"
2 2 "charlie"
3 1 "bravo"
4 2 "alpha"
Expected output:
id(question.id) question upvotecount
2 second ques 3
1 first ques 1
3 third ques 0
(Notice the order & count)
Queries I tried so far:
Closest to my output but require storage in separate variable:
var t = query
.Select(x => new
{
question = x.Id,
count = (from upvotes2 in model.Upvotes
where upvotes2.QuestionId == x.Id
select upvotes2).Count()
})
.OrderByDescending(c => c.count);
foreach (var a in t)
Console.WriteLine("" + a);
What I am trying to make it as
query = query
.Select(x => new Question
{
UpvoteCount = (from upvotes2 in model.Upvotes
where upvotes2.QuestionId == x.Id
select upvotes2).Count()
})
.OrderByDescending(c => c.UpvoteCount);
foreach (var a in query)
Console.WriteLine("" + a);
The latter gives me:
System.NotSupportedException: 'The entity or complex type
mYpROEJT.DataAccess.CodeFirstModel.Question
cannot be constructed in a LINQ to Entities query.
whereas former is close to output which is:
"query" is of type IQueryable<Question>
"Question" is a class generated from Entity and I added a [NotMapped] int UpvoteCount
there
{ question = 5, upcount = 2 }
{ question = 3, upcount = 1 }
{ question = 2, upcount = 0 }
{ question = 1, count = 0 }
{ question = 4, count = 0 }
EDIT 1: To add to original post. I want to return list of Questions and an Upvote count along.