ASP.NET Core下MSSQL关联表Games按Genres分类搜索功能实现问询
Razor Pages 按游戏类型筛选功能实现方案
你的游戏(GamesTable)与类型(GenresTable)为多对多关联关系,通过GameGenre中间表做映射,原有代码的问题是没有通过关联表匹配类型,直接把游戏名和选中类型做了比较。以下是修复后的代码,最终返回的依然是GamesTable类型的集合,不需要修改原有返回结构,不会存在关联后数据无法写入的问题,可直接在现有OnGetAsync方法中完成逻辑:
public async Task OnGetAsync() { var searchGame = from m in _context.gamesTable select m; // 原有按游戏名称筛选逻辑保持不变 if (!string.IsNullOrEmpty(SearchGames)) { searchGame = searchGame.Where(s => s.NameGame.Contains(SearchGames)); } IQueryable<string> searchGenres = from m in _context.genresTable select m.NameGenres; // 修复后的按类型筛选关联逻辑 if (!string.IsNullOrEmpty(SelectGenre)) { // 通过中间表关联类型表,筛选出属于选中类型的所有游戏 searchGame = searchGame.Where(g => _context.GameGenre.Any(gg => gg.IdGame == g.ID && _context.genresTable.Any(ge => ge.ID == gg.IdGenre && ge.NameGenres == SelectGenre) ) ); } GamesTable = await searchGame.ToListAsync(); GenresList = new SelectList(await searchGenres.Distinct().ToListAsync()); }
注意事项
- 请将代码中的
_context.GameGenre替换为你上下文类中GameGenre对应的DbSet属性名,和你现有命名规则保持一致即可。 - 如果你确定
GameGenre中存储的NameGenres冗余字段数据是实时同步的,也可以简化关联逻辑直接查询中间表的NameGenres字段,减少关联查询提升性能。
内容的提问来源于stack exchange,提问作者Kamil
相关产品推荐
相关产品推荐

