Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why throws exception when using Guid.Parse() method?

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?

like image 900
coderhunk Avatar asked Feb 15 '16 06:02

coderhunk


2 Answers

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;
    }
like image 55
Mainul Avatar answered Oct 07 '22 03:10

Mainul


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'.

like image 39
madoxdev Avatar answered Oct 07 '22 03:10

madoxdev