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?
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;
}
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With