LINQ to Entities无法识别方法'System.String ToString()'方法

Kut*_*ith 8 linq-to-entities

string[] userIds = userList.Split(','); // is an array of integers
IList<User> users = (from user in this.repository.Users
                     where userIds.Contains(user.Id.ToString())
                     select user).ToList();
Run Code Online (Sandbox Code Playgroud)

以上查询给出

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

我能做什么?

Rab*_*arb 14

使用可以使用这样的东西,

where userIds.Contains(SqlFunctions.StringConvert((double)user.Id))
Run Code Online (Sandbox Code Playgroud)

代替 where userIds.Contains(user.Id.ToString())

这应该工作


Mar*_*ers 7

避免打电话给ToString.你想要这样的东西:

userIds.Contains(user.Id)
Run Code Online (Sandbox Code Playgroud)

要使此工作,列表userIds必须是具有的类型的集合user.Id.如果你想要整数然后int.Parse用来将字符串转换为整数:

int[] userIds = userList.Split(',').Select(s => int.Parse(s)).ToArray();
Run Code Online (Sandbox Code Playgroud)