比较GUID和LINQ to Entities中的字符串会引发错误 [英] Comparing GUID to string in LINQ to Entites throws error

查看:35
本文介绍了比较GUID和LINQ to Entities中的字符串会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑,这不是重复项.建议的SO链接要我调用 ToString(),但是我正在运行 .COUNT(),并尝试做一个大于比较的事情,所以调用了 ToString()是不正确的答案.

EDIT, this is not a duplicate. The suggested SO links want me to call ToString() but I am running a .COUNT() and trying to do a greater than comparison so calling ToString() is not a correct answer.

我正在尝试使用 IF 快捷方式填充变量,但是在运行它时出现错误

I am trying to fill a variable using the IF shortcut but when I run it I get the error

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

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

我正在运行的代码是

IsAdmin = (db.yaf_prov_RoleMembership
             .Where(rm => rm.UserID == UserKey
                          && rm.RoleID == Guid.Parse("adsfasd654asdf816asdf"))
             .Count() > 0) ? true : false;

如果我删除了 Guid.Parse 并进行了直接比较,那么我会得到错误

If I take away the Guid.Parse and do a straight up comparison then I get the error

Operator ==不能应用于System.Guid和String类型的操作数

Operator == cannot be applied to operands of type System.Guid and String

要将GUID与LINQ查询中的字符串进行比较需要做什么?

What needs to be done in order to compare a GUID to a string in a LINQ query?

推荐答案

不知道Dave为什么删除他的答案-您应该将字符串解析移出存储表达式.否则,Entity Framework尝试将 Guid.Parse 方法调用转换为SQL,但这样做失败:

Don't know why Dave deleted his answer - you should just move string parsing out of store expression. Otherwise Entity Framework tries to convert Guid.Parse method call to SQL, and fails to do that:

var adminRoleID = Guid.Parse("adsfasd654asdf816asdf");

还使用 Queryable.Any 简化查询:

IsAdmin = db.yaf_prov_RoleMembership
            .Any(rm => rm.UserID == UserKey && rm.RoleID == adminRoleID);

这篇关于比较GUID和LINQ to Entities中的字符串会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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