【问题标题】: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&lt;&lt;anonymous type: string Access&gt;&gt;' 隐式转换为 'System.Collections.Generic.IEnumerable&lt;string&gt;'。存在显式转换(您是否缺少演员表?)

这是我的模型:

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 typesIEnumerable,而您需要 StringsIEnumerable

    【讨论】:

      【解决方案2】:

      我认为您只需要执行以下操作:

      private async Task<IEnumerable<string>> GetAccessLevels(Guid roleId)
      {
          return await AccessLevels.Where(x => x.RoleId == roleId).Select(x=> x.Access).ToListAsync();
      }
      

      无需在Select 中创建匿名对象。

      【讨论】:

        猜你喜欢
        • 2015-08-04
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        • 2013-01-17
        • 1970-01-01
        • 2021-01-06
        • 2021-09-07
        相关资源
        最近更新 更多