【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: string Access>>' to 'System.Collections.Generic.IEnumerable<string>'无法将类型“System.Collections.Generic.List<<匿名类型:字符串访问>>”隐式转换为“System.Collections.Generic.IEnumerable<string>”
【发布时间】:2020-07-31 02:43:45
【问题描述】:
我想在函数中返回字符串列表:
private async Task<IEnumerable<string>> GetAccessLevels(Guid roleId)
{
return await AccessLevels.Where(x => x.RoleId == roleId).Select(x=>new {x.Access }).ToListAsync();
}
但它显示了这个错误:
无法将类型 'System.Collections.Generic.List<<anonymous type: string Access>>' 隐式转换为 'System.Collections.Generic.IEnumerable<string>'。存在显式转换(您是否缺少演员表?)
这是我的模型:
public Guid RoleId { get; set; }
public string Access { get ; set; }
我该如何解决这个问题?
【问题讨论】:
标签:
c#
asp.net-mvc
entity-framework
entity-framework-core
【解决方案1】:
只要改变这个:
Select(x => new { x.Access })
到这里:
Select(x => x.Access)
原因是,new 使您的查询返回 Anonymous types 的 IEnumerable,而您需要 Strings 的 IEnumerable。
【解决方案2】:
我认为您只需要执行以下操作:
private async Task<IEnumerable<string>> GetAccessLevels(Guid roleId)
{
return await AccessLevels.Where(x => x.RoleId == roleId).Select(x=> x.Access).ToListAsync();
}
无需在Select 中创建匿名对象。