Getting the first result from a LINQ query - why does ElementAt<T>(0) fails when First<T>() succeeds
Posted
by Mr Roys
on Stack Overflow
See other posts from Stack Overflow
or by Mr Roys
Published on 2010-04-16T02:13:46Z
Indexed on
2010/04/16
2:23 UTC
Read the original article
Hit count: 339
I have a method AddStudent() which looks for a student with the same name and returns an existing student from the database if there is a student with the same name, otherwise it creates a new student and adds it to the database.
I'm curious why se = students.First<StudentEntity>();
succeeds when se = students.ElementAt<StudentEntity>(0);
fails when I try to get the first result from the LINQ query. Aren't the two methods the same?
The full code for the method is shown below.
public Student AddStudent(string name)
{
using (SchoolEntities db = new SchoolEntities())
{
// find student with same name via LINQ
var students = from s in db.StudentEntitySet
where s.name == name
select s;
StudentEntity se = default(StudentEntity);
// if student with the same name is already present, return
// that student
if (students.Count<StudentEntity>() > 0)
{
// if i use ElementAt, if fails with a "LINQ to Entities does not
// recognize the method 'StudentEntity ElementAt[StudentEntity]
// (System.Linq.IQueryable`1[StudentEntity], Int32)' method,
// and this method cannot be translated into a store expression.",
// but not when I use First. Why?
// se = students.ElementAt<StudentEntity>(0);
se = students.First<StudentEntity>();
}
else
{
// passing 0 for first parameter (id) since it's represented by
// a BigInt IDENTITY field in the database so any value
// doesn't matter.
se = StudentEntity.CreateStudentEntity(0, name);
db.AddToStudentEntitySet(se);
db.SaveChanges();
}
// create a Student object from the Entity object
return new Student(se);
}
}
Thanks!
© Stack Overflow or respective owner