Onl*_*ere 15 c# linq int casting
这是我正在尝试做的事情:
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();
}
Run Code Online (Sandbox Code Playgroud)
我不得不转换为Int32,因为List<int?>当方法返回时我无法返回List<int>.
关于如何解决这个简单问题的任何建议?
And*_*ber 24
而不是这个:
Select(a => Convert.ToInt32(a.RoleId))
Run Code Online (Sandbox Code Playgroud)
做这个:
Select(a => a.RoleId.Value)
Run Code Online (Sandbox Code Playgroud)
原因在于错误描述; 当您通过IQueryable进行这些查询时,选择器中使用的方法必须是可以转换为SQL查询或函数的方法.在这种情况下Convert.ToInt32()不是这样的方法.对于允许的int字段null,使用.NET .Value属性确实有效.
但是请注意,如果你RoldId是这样,这将不起作用null.你会得到一个InvalidOperationException.如果支持字段为null,您可能希望返回设置值:
Select(a => a.RoleId.HasValue ? a.RoleId.Value : int.MinValue)
Run Code Online (Sandbox Code Playgroud)
如果有值,这将返回值,如果没有,则返回值int.MinValue.
| 归档时间: |
|
| 查看次数: |
21281 次 |
| 最近记录: |