如何使用linq到实体检索索引处的项目 [英] How do I retrieve an item at an index using linq to entities
问题描述
//大家好,我已经尝试了几种方法。我的目的是从问题库中获取一些具有不同项目的随机问题。所以我根据问题库的大小生成了一些随机索引,例如40,并将它们存储在一个整数数组中。我现在循环遍历数组以检索数组索引处的项目。每当我尝试几个想法时,我最终都会收到此错误。
LINQ to Entities无法识别方法'CBTDLCF.QuestionTable ElementAtOrDefault [QuestionTable](System.Linq.IQueryable`1 [CBTDLCF.QuestionTable],Int32 )'方法,并且此方法无法转换为商店表达式。
//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.
//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
推荐答案
尝试:
Try:
var element = context.QuestionTables.ToList()[index];
基本上,您试图在表中获取特定的行号。没有SQL等价物(至少是一种简单的方法)来实现这一目标。添加 .ToList()
您正在强制立即执行查询并将结果带入内存,特别是 List $ c $对象。这有一个通过索引访问数据的简单方法。
这个问题是,如果你的表很大,你会减少很多数据。理想情况下,您应该根据源表中的键或列查询表。
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.
这篇关于如何使用linq到实体检索索引处的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!