LINQ to Entities不识别方法'Int32 ToInt32(System.Object)',并且此方法无法转换为存储表达式。

17

这是我想要做的事情:

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,因为当方法需要返回一个List<int>时,我无法返回一个List<int?>

有什么建议可以解决这个简单的问题吗?


我认为“Convert”函数在LINQ to Entities中无法使用,你可以尝试使用db.AccountRules.AsEnumerable() 然后进行剩下的操作。 - V4Vendetta
3个回答

28

不要这样做:

Select(a => Convert.ToInt32(a.RoleId))

执行以下操作:

Select(a => a.RoleId.Value)

报错信息中已经说明了原因;当您通过IQueryable执行这些查询时,选择器内使用的方法必须是可以翻译成SQL查询或函数的内容。在此情况下,Convert.ToInt32()不是这样的方法。对于允许nullint字段,可以使用.NET的.Value属性。

请注意,如果RoldIdnull,则此方法将无法工作,您将收到InvalidOperationException。如果后台字段为空,您可能希望返回一个默认值:

Select(a => a.RoleId.HasValue ? a.RoleId.Value : int.MinValue)

如果有值,则返回该值,否则返回 int.MinValue


6
使用以下代码: Select(a => (int)a.RoleId)

1
这个方法对我有效。@AndrewBarber的答案没用。谢谢muthuvel。 - user2330678
1
这个有效了,其他的没用 - 谢谢 - Lyall

0
尝试从db.Accounts中获取List对象并进行操作。 这对我有效。
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();
}

不要用这个,试试这个。

public List<int> GetRolesForAccountByEmail(string email)
    {
    var account = db.Accounts.SingleOrDefault(a => a.Email == email);
    if (account == null) return new List<int>();
    List<AccountRoles> accountRoles= db.AccountRoles.ToList<AccountRoles>();
    return accountRoles.Where(a => a.AccountId == account.AccountId).Select(a => Convert.ToInt32(a.RoleId)).ToList();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接