【发布时间】:2021-10-17 10:58:12
【问题描述】:
我正在尝试在 netcore 中实现干净的架构,但出现运行时错误 InvalidCastException:无法将“System.Collections.Generic.List”类型的对象转换为 System.Collections.Generic.IEnumerable
在 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<T>是IEnumerable<T>的实现 -
请更清楚地告诉我在哪里尝试?在存储库中或来自 mediatr 的请求中
-
in
GetMatchDetailAsync()返回值而不进行强制转换 -
因为你试图将
List<anonymous>转换为IEnumerable<MatchesDetail>,这是完全错误的。
标签: linq .net-core asp.net-core-mvc clean-architecture