【问题标题】:LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expressionLINQ to Entities 无法识别方法 'Int32 ToInt32(System.Object)' 方法,并且此方法无法转换为存储表达式
【发布时间】:2012-04-12 05:07:29
【问题描述】:

这是我想要做的:

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&lt;int&gt; 时,我无法返回 List&lt;int?&gt;

关于如何解决这个简单问题的任何建议?

【问题讨论】:

  • 我认为Convert 函数不能与 LINQ to Entities 一起使用,您是否可以先执行 db.AccountRules.AsEnumerable(),然后再执行其他操作

标签: c# linq casting int


【解决方案1】:

而不是这个:

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

【讨论】:

    【解决方案2】:

    使用这个: 选择(a => (int)a.RoleId)

    【讨论】:

    • 这对我有用。 @AndrewBarber 的回答没有。谢谢muthuvel。
    • 是的,这个在其他人没有的地方工作 - 谢谢
    【解决方案3】:

    尝试从 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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多