11

I am working with a WebApi application where I have written a method to get the Student using the following code:

    public Student GetStudent(string studentId)
    {
        var student = this.context.Students.FirstOrDefault(x => x.Id == Guid.Parse(studentId));
        return student;
    }

Here the studentId is getting from a WebApi call. But when I tried to run this application it throws an exception like:

Additional information: LINQ to Entities does not recognize the method 'System.Guid Parse(System.String)' method, and this method cannot be translated into a store expression.

Is there any one tell me why this is occurred and how can I resolve this issue?

coderhunk
  • 153
  • 1
  • 6

4 Answers4

16

First of all when you use EntityFramework, it will try to convert the Guid.Parse() method to a SQL and it fails to do that as it cannot convert to SQL statement/ 'store expression'.

You should just move the string parsing out of store expression and parse the string to Guid value before using it in the Query.

    public Student GetStudent(string studentId)
    {
        var stdId = Guid.Parse(studentId);
        var student = this.context.Students.FirstOrDefault(x => x.Id == stdId);
        return student;
    }
Mainul
  • 879
  • 7
  • 10
2

You may try this approach:

public Student GetStudent(string studentId)
{
    var student = (from c in this.context.Students
                  let guidId = Guid.Parse(studentId)
                  where c.Id == guidId
                  select c).FirstOrDefault();

    return student;
}

In this approach let allows You to create new temporary variable, that might be used later in LinqToEntities query.

I agree with @Mainul answer regarding reason of exception:

Firt of all when you use EntityFramework, this will tried to convert the Guid.Parse() method to a SQL and it fails to do that as it cannot convert to SQL statement/ 'store expression'.

madoxdev
  • 3,770
  • 1
  • 24
  • 39
0

As stated here

Entity Framework is trying to execute your projection on the SQL side, where there is no equivalent to string.Format. Use AsEnumerable() to force evaluation of that part with Linq to Objects

Your case tries to evaluate Guid.Parse transformed to SQL query which is not found in SQL.

This happened with me also when I was trying to operate date part as-

var query = db.Table.Where(f=> f.Date == paramDate.Date.AddDays(-1)).ToList();
Community
  • 1
  • 1
Manoz
  • 6,507
  • 13
  • 68
  • 114
0

Better yet, I may add, instead of string studentId for signature, use Guid studentId since that's what you need anyway. And this makes it clear that studentId is a guid, not a string to the caller. If the caller wants to use the the returning Student object, you don't want him to do this string studentid = student.Id. You want him to do this Guid myStudentId = student.Id.

Zuzlx
  • 1,246
  • 14
  • 33