Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Adding / Displaying Related Items to the Detail View

$
0
0

Hi,

I am building a video game help site.  It runs similar to a store shop website.  Its connected to a SQL Server under one database with about 5 tables. 

Using some of the MSDN tutorials, I have had successfully joined several of the tables using LINQ, and displayed the data right down to the details page.

The issue that is stumping me, is that I need to now want to bring in related data (from several tables). This data has a one with many relationships.  From what I gathered you can not bring this into a single view?  The only way I have had some success, is when I joined all the needed tables. The output was the tables with single data entries being stamped out repeatedly over and over, for every related entry in the tables with multiple relationships. 

I am looking to get guided in the right direction, as I might not be using the right terminology, or could be shown an example, etc.  I feel like the answer is in front of me, but I am looking in the wrong spot.

Thank you in advance,

Some of my code below:

Tables:
(Everything revolves around GameId)

Game - Contains title, about information and locations to cover image
Pricelist - Price information
PlayerGameRating - Rating of 1 to 5, per player, per game.

GameMedia - Zero to Unknown number of entries containing video/picture location, title and description.
GameHelp - Zero to Unknown number of entries containing video/picture location, title and description.

Code:

GamesController.cs (Contains just the details to display whole library and the detail page.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using GameCloud.Models;
using GameCloud.Models.GamesViewModels;
using System.Dynamic;
using System.Data.SqlTypes;
namespace GameCloud.Controllers
{
    public class GamesController : Controller
    {
        private readonly GameCloudContext _context;

        public GamesController(GameCloudContext context)
        {
            _context = context;
        }

        // GET: Games
        public async Task<IActionResult> Index(string sortOrder, string searchString, string currentFilter, int? page)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
            ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
            ViewData["DevSortParm"] = String.IsNullOrEmpty(sortOrder) ? "dev_desc" : "";
            ViewData["GenreSortParm"] = String.IsNullOrEmpty(sortOrder) ? "genre_desc" : "";
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            ViewData["CurrentFilter"] = searchString;

            var gamerating = from r in _context.PlayerGameRating
                             group r by r.GameId into gameAvg
                             select new { GameId = gameAvg.Key, AverageRating = gameAvg.Average(p => (decimal?)p.RatingStars ?? 0) };

            var finalrating = from gameInfo in _context.Game
                              join rate in gamerating on gameInfo.GameId equals rate.GameId into gj
                              from subgame in gj.DefaultIfEmpty()
                              select new { gameInfo.GameId, gameInfo.GameTitle, gameInfo.GameReleaseDate, gameInfo.GameRating, gameInfo.GameStudio, gameInfo.GameSynop, gameInfo.GameGenre, gameInfo.GameAssests, AverageRating = (subgame == null ? 0 : subgame.AverageRating) };


            var Qry = from c in finalrating
                      join g in _context.PriceList on c.GameId equals g.GameId
                      //orderby c.GameReleaseDate descending
                      select new GameLibViewModel()
                      {
                          GameId = c.GameId,
                          GameTitle = c.GameTitle,
                          GameReleaseDate = c.GameReleaseDate,
                          GameReleaseDate2 = c.GameReleaseDate,
                          GameAssets = c.GameAssests,
                          GameRating = c.GameRating,
                          GameSynop = c.GameSynop,
                          AverageRating = c.AverageRating,
                          Studio = c.GameStudio,
                          Genre = c.GameGenre,
                          Price = g.RetailCdn,
                          PriceUs = g.RetailUsd
                      };
            if (!String.IsNullOrEmpty(searchString))
            {
                Qry = Qry.Where(s => s.GameTitle.Contains(searchString)
                                       || s.Studio.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "title_desc":
                    Qry = Qry.OrderByDescending(s => s.GameTitle);
                    break;
                case "dev_desc":
                    Qry = Qry.OrderByDescending(s => s.Studio);
                    break;
                case "Date":
                    Qry = Qry.OrderBy(s => s.GameReleaseDate2);
                    break;
                case "date_desc":
                    Qry = Qry.OrderByDescending(s => s.GameReleaseDate2);
                    break;
                case "genre_desc":
                    Qry = Qry.OrderByDescending(s => s.Genre);
                    break;
                default:
                    Qry = Qry.OrderByDescending(s => s.GameReleaseDate2);
                    break;
            }
            int pageSize = 4;
            return View(await PaginatedList<GameLibViewModel>.CreateAsync(Qry.AsNoTracking(),page ?? 1, pageSize));
        }


        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();

            }


            //WORKING
             var gamerating = from r in _context.PlayerGameRating
                               group r by r.GameId into gameAvg
                               select new { GameId = gameAvg.Key, AverageRating = gameAvg.Average(p => (decimal?)p.RatingStars ?? 0) };

              var finalrating = from gameInfo in _context.Game
                                join rate in gamerating on gameInfo.GameId equals rate.GameId into gj
                                from subgame in gj.DefaultIfEmpty()
                                select new { gameInfo.GameId, gameInfo.GameTitle, gameInfo.GameReleaseDate, gameInfo.GameRating, gameInfo.GameStudio, gameInfo.GameDevsite, gameInfo.GameLocPage, gameInfo.GameExtSynop, gameInfo.GameGenre, gameInfo.GameAssests, AverageRating = (subgame == null ? 0 : subgame.AverageRating) };

              var Qry = from c in finalrating
                        join g in _context.PriceList on c.GameId equals g.GameId
                        where c.GameId == id
                        select new SingleGameViewModel()
                        {
                            GameId = c.GameId,
                            GameTitle = c.GameTitle,
                            GameReleaseDate = c.GameReleaseDate,
                            GameAssets = c.GameAssests,
                            GameRating = c.GameRating,
                            GameSynopExt = c.GameExtSynop,
                            AverageRating = c.AverageRating,
                            Studio = c.GameStudio,
                            StudioSite = c.GameDevsite,
                            GameSite = c.GameLocPage,
                            Genre = c.GameGenre,
                            Price = g.RetailCdn,
                            PriceUs = g.RetailUsd


                        };
            var game = await Qry
                .SingleOrDefaultAsync(m => m.GameId == id);
            if (game == null)
            {
                return NotFound();
            }

            return View(game);


        }


    }
}

Partial View Detail Page:

@using Microsoft.AspNetCore.Mvc.ViewFeatures
@using GameCloud.Models.GamesViewModels
@model SingleGameViewModel<div class="body-content">
    @{
        ViewData["Title"] = "Details";

    }

    <h2>Details</h2><div><h4>Game</h4><hr /><dl class="dl-horizontal"><dt>
                @Html.DisplayNameFor(model => model.GameTitle)</dt><dd>
                @Html.DisplayFor(model => model.GameTitle)</dd><dt>
                @Html.DisplayNameFor(model => model.GameAssets)</dt><dd><a href="@Html.DisplayFor(model => model.GameSite)"><img src="@Html.DisplayFor(model => model.GameAssets)" alt="Cover" /></a></dd><dt>
                @Html.DisplayNameFor(model => model.Studio)</dt><dd><a href="@Html.DisplayFor(model => model.StudioSite)">@Html.DisplayFor(model => model.Studio)</a></dd><dt>
                @Html.DisplayNameFor(model => model.GameReleaseDate)</dt><dd>
                @Html.DisplayFor(model => model.GameReleaseDate)</dd><dt>
                @Html.DisplayNameFor(model => model.Genre)</dt><dd>
                @Html.DisplayFor(model => model.Genre)</dd><dt>
                @Html.DisplayNameFor(model => model.GameRating)</dt><dd>
                @Html.DisplayFor(model => model.GameRating)</dd><dt>
                @Html.DisplayNameFor(model => model.AverageRating)</dt><dd><p>@Html.DisplayFor(model => model.AverageRating) out of 5</p></dd><dt>
                @Html.DisplayNameFor(model => model.Price)</dt><dd>
                @Html.DisplayFor(model => model.Price)</dd><dt>
                @Html.DisplayNameFor(model => model.GameSynopExt)</dt><dd>
                @Html.DisplayFor(model => model.GameSynopExt)</dd></dl></div><div id="media">
        Related Media Goes Here</div><div id="media">
        Related Help Media Goes Here</div><div><a asp-action="Index">Back to List</a></div></div>

ViewModel For Details:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace GameCloud.Models.GamesViewModels
{
    public class SingleGameViewModel
    {
        [Key]
        public int GameId { get; set; }
        public string GameAssets { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string GameTitle { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string GameRating { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string Genre { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string Studio { get; set; }

        public string StudioSite { get; set; }

        public string GameSite { get; set; }
        /// <summary>
        ///
        /// </summary>
        ///
        public string GameSynopExt { get; set; }

        [DisplayFormat(DataFormatString = "{0:MMM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? GameReleaseDate { get; set; }

        [DisplayFormat(DataFormatString = "{0:0.0}")]
        public decimal AverageRating { get; set; }

        /// <summary>
        /// Below are commented out attempts when I tried to bring the related data in
        /// </summary>
        ///
        /*public decimal Price { get; set; }
        public decimal PriceUs { get; set; }
        public ICollection <GameHelp> GameHelps { get; set; }

        public virtual ICollection<GameMedia> GameMedias { get; set; }
        public virtual Game Game { get; set; }
        public IEnumerable<GameHelpViewModel> _GameHelp { get; set; }*/

        //  public IEnumerable <GameHelp> GameHelp { get; set; }

      /*  public int GameHelpId { get; set; }
        public string GameHelpTitle { get; set; }
        public string GameHelpSynop { get; set; }
        public string GameHelpLink { get; set; }
        public string GameHelpIcon { get; set; }
        [DisplayFormat(DataFormatString = "{0:MMM/dd/yyyy}")]
        public DateTime? CreateStamp { get; set; }*/







    }

}


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>