Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
//Hello people, I've tried several ways of going about this. My aim is to get some random questions from a question bank with distinct items. So I generated some random indexes based on the size of my question bank say 40 for example and get them stored in an array of integers. I now looped through the array to retrieve an item at the index of the array. I ended up receiving this error each time I try several ideas.

LINQ to Entities does not recognize the method 'CBTDLCF.QuestionTable ElementAtOrDefault[QuestionTable](System.Linq.IQueryable`1[CBTDLCF.QuestionTable], Int32)' method, and this method cannot be translated into a store expression.

C#
//This is what I wrote
public List<QuestionTable> RandomQuestionWIthDistinctElement()
{
     Random randIndex = new Random();
     int totalQuestions = context.QuestionTables.Count();
     int[] randomIndex = new int[totalQuestions];
     List<QuestionTable> d = new List<QuestionTable>();

     for (int i = 0; i < totalQuestions; i++)
     {
           randomIndex[i] = randIndex.Next(1,totalQuestions);
     }

     for (int i = 0; i < randomIndex.Distinct().Count(); i++)
     {
           var element = context.QuestionTables.ElementAt(index);
           d.Add(element);
     }

     return d;
}

//So I make use if the function in my Page_Load like this
//
var result = RandomQuestionWIthDistinctElement().Take(5).ToList();
questionTable = ToDataTable(result);//convert to sql datatable
//I don't know why I'm getting this error
Posted
Updated 7-Jul-15 7:46am
v2
Comments
virusstorm 7-Jul-15 13:47pm    
Where exactly are you getting this error?
matmape 7-Jul-15 13:56pm    
at var element = context.QuestionTables.ElementAt(index);

1 solution

Try:
C#
var element = context.QuestionTables.ToList()[index];


Basically, you are trying to get a specific row number in your table. There is no SQL equivalent (at least a simple way) to get this. Adding the .ToList() you are forcing an immediate execution of the query and bring the results into memory, specifically into a List object. This has a nice easy way to access the data via an index.

The issue with this is, if your table is large, you are bringing down a lot of data. Ideally, you should be querying the table based on a key or column in the source table.
 
Share this answer
 
Comments
matmape 7-Jul-15 14:33pm    
Thanks @virusstorm, I really appreciate it. It worked as expected

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900