LINQ to Entities不识别方法“Int32 ToInt32(System.Object)”方法,并且此方法无法转换为存储表达式 [英] LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression
问题描述
这里是我想做的:
public List<int> GetRolesForAccountByEmail(string email)
{
var account = db.Accounts.SingleOrDefault(a => a.Email == email);
if (account == null) return new List<int>();
return db.AccountRoles.Where(a => a.AccountId == account.AccountId).Select(a => Convert.ToInt32(a.RoleId)).ToList();
}
我必须转换为Int32,因为我不能返回<$ c $当方法返回 List< int>
时,列表
有关如何解决这个简单问题的任何建议吗?
Any suggestions on how to solve this simple problem?
推荐答案
$ b
Instead of this:
Select(a => Convert.ToInt32(a.RoleId))
这样做:
Select(a => a.RoleId.Value)
原因是在错误描述中;当您通过IQueryable执行这些查询时,在选择器中使用的方法必须是可以转换为SQL查询或函数的东西。在这种情况下, Convert.ToInt32()
不是这样的方法。对于 int
允许使用 null
的字段,使用.NET .Value $ c $
The reason is in the error description; when you are doing these queries through IQueryable, the methods being used within the selector have to be something that can be translated into a SQL query or function. In this case Convert.ToInt32()
is not such a method. For int
fields with null
allowed, using the .NET .Value
property does work, though.
请注意,如果您的 RoldId
null
。您将获得 InvalidOperationException
。如果支持字段为null,您可能想要返回一个设置值:
Note that this would not work if your RoldId
is null
, however. You'll get an InvalidOperationException
. You might want to return a set value instead if the backing field is null:
Select(a => a.RoleId.HasValue ? a.RoleId.Value : int.MinValue)
, int.MinValue
如果没有。
这篇关于LINQ to Entities不识别方法“Int32 ToInt32(System.Object)”方法,并且此方法无法转换为存储表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!