![](/img/trans.png)
[英]LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression
[英]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,因為當方法返回List<int?>
時,我無法返回List<int?>
List<int>
。
關於如何解決這個簡單問題的任何建議?
而不是這個:
Select(a => Convert.ToInt32(a.RoleId))
做這個:
Select(a => a.RoleId.Value)
原因在於錯誤描述; 當您通過IQueryable進行這些查詢時,選擇器中使用的方法必須是可以轉換為SQL查詢或函數的方法。 在這種情況下, Convert.ToInt32()
不是這樣的方法。 對於允許為null
int
字段,使用.NET .Value
屬性確實有效。
請注意,如果您的RoldId
為null
,則RoldId
操作null
。 你會得到一個InvalidOperationException
。 如果支持字段為null,您可能希望返回設置值:
Select(a => a.RoleId.HasValue ? a.RoleId.Value : int.MinValue)
如果有值,則返回值,否則返回int.MinValue
。
使用:選擇(a =>(int)a.RoleId)
嘗試從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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.