Getting the first result from a LINQ query - why does ElementAt <T> (0) fail when First <T> () succeeds?

I have an AddStudent () method that searches 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 he creates a new student and adds it to the database.

I am curious why it se = students.First<StudentEntity>();succeeds when it se = students.ElementAt<StudentEntity>(0);fails, when I try to get the first result from a LINQ query. Are these two methods the same?

The full method code 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 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);
    }
}

Thank!

+3
source share
1 answer

, ElementAt - , Entity Framework , SQL.

First, Entity Framework TOP 1 SQL-. . ElementAt, (ROW_NUMBER()), , , .

Entity Framework. ElementAt .


:

se = students.AsEnumerable().ElementAt<StudentEntity>(0);

Entity Framework "" - AsEnumerable(), ( ) , , want ( ).

First(), , 1 , . , - 5- 10- - , .

+8

Source: https://habr.com/ru/post/1741377/


All Articles