Comparing GUID to string in LINQ to Entites throws error [duplicate]

僤鯓⒐⒋嵵緔 提交于 2020-11-29 06:17:57

问题


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.

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

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

The code I am running is

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

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

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

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


回答1:


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");

Also use Queryable.Any to simplify your query:

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



回答2:


The key part of your first error reponse is this: [...]into a store expression. If you parse the guid first and store in a var, I think it should work:

 var guid = Guid.Parse("adsfasd654asdf816asdf");
 IsAdmin = db.yaf_prov_RoleMembership
             .Any(rm => rm.UserID == UserKey && rm.RoleID == guid );

Whenever you do operations that the 'thing' that executes your LINQ queries does not know how to handle, you'll get this error. In this case, it's entity framework not knowing how to translate Guid.Parse into an SQL statement/ 'store expression'.

EDIT: Modified to use .Any. as per Sergey Berezovskiy's answer



来源:https://stackoverflow.com/questions/25354121/comparing-guid-to-string-in-linq-to-entites-throws-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!