InvalidCastException:无法将“System.Collections.Generic.List”类型的对象转换为 System.Collections.Generic.IEnumer

Posted

技术标签:

【中文标题】InvalidCastException:无法将“System.Collections.Generic.List”类型的对象转换为 System.Collections.Generic.IEnumerable【英文标题】:InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List to System.Collections.Generic.IEnumerable 【发布时间】:2021-10-17 10:58:12 【问题描述】:

我正在尝试在 netcore 中实现干净的架构,但出现运行时错误

在 WebUI 中,我有像这样的 Match 控制器和 ViewAllMatch Action

public async Task<IActionResult> ViewAllMatch()
        
            var matches = await _mediator.Send(new GetMatchesDetail());
            return View(matches);
        

在应用层我有这样的查询:

public class GetMatchesDetail : IRequest<IEnumerable<MatchesDetail>>
    
    
    public class MatchesDetail
    
        public string MatchId  get; set; 
        public int MatchNumer  get; set; 
        public DateTime DateMatch  get; set; 
        public TimeSpan TimeMatch  get; set; 
        public int MatchYear  get; set; 
        public string SeasonId  get; set; 
        public string Round  get; set; 
        /// <summary>
        /// Set value to Qualified for Qualified and Final for Final Round
        /// </summary>
        public string Stage  get; set; 
        public string SubStage  get; set; 
        public string HTeam  get; set; 
        public string HTeamCode  get; set;  //For Flag get from Table Team from Foreign Key TeamName
        public int HGoal  get; set; 
        public int GGoal  get; set; 
        public string GTeam  get; set; 
        public string GTeamCode  get; set; 
        public string WinNote  get; set; 
        public string Stadium  get; set; 
        public string Referee  get; set; 
        public long Visistors  get; set; 
        public string Status  get; set; 
    

    public class GetMatchesHandler : IRequestHandler<GetMatchesDetail, IEnumerable<MatchesDetail>>
    
        private readonly IMatchRepository _matchRepository;
       
        public GetMatchesHandler(IMatchRepository matchRepository)
        
            _matchRepository = matchRepository;
        

        public async Task<IEnumerable<MatchesDetail>> Handle(GetMatchesDetail request, CancellationToken cancellationToken)
        
            var matchlistview = await _matchRepository.GetMatchDetailAsync();

            return matchlistview;
        
    

还有 matchRepository 的代码来获取 Infastructure 中的所有匹配项。

public async Task<IEnumerable<MatchesDetail>> GetMatchDetailAsync()
        
            var matchDetailList = (from match in _context.Matches
                                   join team1 in _context.Teams on match.HTeam equals team1.TeamName
                                   join team2 in _context.Teams on match.GTeam equals team2.TeamName
                                   join season in _context.Seasons on match.SeasonId equals season.SeasonId
                                   select new
                                   
                                       match.MatchId,
                                       match.MatchNumber,
                                       match.DateMatch,
                                       match.TimeMatch,
                                       match.MatchYear,
                                       match.SeasonId,
                                       season.SeasonName,
                                       match.Round,
                                       match.Stage,
                                       match.SubStage,
                                       match.HTeam,
                                       HTeamCode = team1.TeamCode,
                                       match.HGoal,
                                       match.GGoal,
                                       match.GTeam,
                                       GTeamCode = team2.TeamCode,
                                       match.WinNote,
                                       match.Stadium,
                                       match.Referee,
                                       match.Visistors

                                   );

            return (IEnumerable<MatchesDetail>)await matchDetailList.ToListAsync();
        

完整代码已上传至 Github https://github.com/nguyentuananh921/Betting.git。 了解更多详情。

感谢您的帮助。 当我有更多实体并且我想在 WebUI 中查看的模型包含域中的许多实体时,我对干净架构中的模型感到非常困惑。

【问题讨论】:

不强制转换试试看,List&lt;T&gt;IEnumerable&lt;T&gt; 的实现 请更清楚地告诉我在哪里尝试?在存储库中或来自 mediatr 的请求中 in GetMatchDetailAsync() 返回值而不进行强制转换 因为你试图将List&lt;anonymous&gt; 转换为IEnumerable&lt;MatchesDetail&gt;,这是完全错误的。 【参考方案1】:

感谢您的帮助。

我有这样修改 public IEnumerable GetMatchDetailAsync()。

public IEnumerable<MatchesDetail> GetMatchDetailAsync()
              

        #region TryOther way
        var matchQuery = (from match in _context.Matches
                               join team1 in _context.Teams on match.HTeam equals team1.TeamName
                               join team2 in _context.Teams on match.GTeam equals team2.TeamName
                               join season in _context.Seasons on match.SeasonId equals season.SeasonId
                               select new
                               
                                   #region selectResult
                                   //Remove to clear Select what I want to get.
                                   #endregion

                               );
        MatchesDetail matchesDetail = new MatchesDetail();
        List<MatchesDetail> retList = new List<MatchesDetail>();
        //IEnumerable<MatchesDetail> retList;
        foreach (var item in matchQuery)
        
            #region ManualMapping
                matchesDetail.MatchId = item.MatchId;
                //other field mapping

            #endregion
            retList.Add(matchesDetail);
        
        #endregion
        return retList;

    

它的工作原理

【讨论】:

您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于InvalidCastException:无法将“System.Collections.Generic.List”类型的对象转换为 System.Collections.Generic.IEnumer的主要内容,如果未能解决你的问题,请参考以下文章

InvalidCastException:无法将“System.DBNull”类型的对象转换为“System.Nullable`1[System.Int32]”[重复]

System.InvalidCastException: 无法将类型为“LabelManager2.ApplicationClass”的 COM对象强制转换为

InvalidCastException:无法使用Unity(C#)从源类型转换为目标类型

防止在工作目录中加载 dll,InvalidCastException Type A 无法转换为 Type B

将程序集加载到单独的 AppDomain 中,得到 InvalidCastException

如何将“IStorageItem”的实现传递给 DataPackage.SetStorageItems(items) 并且不会在 UWP 上引发 InvalidCastException?