为什么在使用Guid.Parse()方法时引发异常? [英] Why throws exception when using Guid.Parse() method?

查看:102
本文介绍了为什么在使用Guid.Parse()方法时引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WebApi应用程序,其中我编写了一种使用以下代码来获取Student的方法:

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;
    }

这里,studentId是从WebApi呼叫中获取的.但是,当我尝试运行此应用程序时,它会引发类似以下的异常:

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

其他信息:LINQ to Entities无法识别方法'System.Guid Parse(System.String)',并且该方法无法转换为商店表达式.

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?

推荐答案

首先,当您使用 EntityFramework 时,它将尝试转换 Guid.Parse()SQL的方法,它无法执行此操作,因为它无法转换为SQL语句/存储表达式".

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

您应该只将解析的字符串移出商店表达式,然后将其解析为 Guid 值,然后在查询中使用它.

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;
    }

这篇关于为什么在使用Guid.Parse()方法时引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆