I want to display the Sum.Slots of all instances of CompendiumId in QualificationBatch and likewise, all the Sum.Seats of all instances of CompendiumId in SAP, and display it in a table like this:
Compendium |Sum.Seats |Sum.Slots
Id1 |Seats1 |Slots1
Id2 |Seats2 |Slots2
After a lot of reading, I think using GroupBy could do this, but I couldn't get it to work as I'm fairly new with everything, even with the basics such as manipulating a List or an IEnumerable. This is what I have so far:
Models
public class Compendium
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<QualificationBatch> QualificationBatches { get; set; }
public virtual ICollection<SAP> SAPs { get; set; }
}
public class QualificationBatch
{
public int Id { get; set; }
public int CompendiumId { get; set; }
public int Slots { get; set; }
public virtual Compendium Compendium { get; set; }
}
public class SAP
{
public int Id { get; set; }
public int CompendiumId { get; set; }
public int Seats { get; set; }
public virtual Compendium Compendium { get; set; }
}
ViewModel
public class SAPSummaryViewModel
{
public int Id { get; set; } //Compendium
public int Slots { get; set; } //QualificationBatch
public int Seats { get; set; } //SAP
}
Controller
public ActionResult Index()
{
List<SAPSummaryViewModel> SAPSummaryViewModelList = new List<SAPSummaryViewModel>();
var sapsummarylist = (from SP in db.SAPs
join Comp in db.Compendia on SP.CompendiumId equals Comp.Id
select new {Comp.Id, SP.Seats });
sapsummarylist.GroupBy(i => i.Id).Select(group =>
new
{
Id = group.Key,
Sum = group.Sum(item => item.Seats)
});
foreach (var item in sapsummarylist)
{
SAPSummaryViewModel objcvm = new SAPSummaryViewModel();
objcvm.Id = item.Id;
objcvm.Seats = item.Seats;
SAPSummaryViewModelList.Add(objcvm);
}
return View(SAPSummaryViewModelList);
}
I'm open to other ways of doing this, I'm just putting the code for my controller above to show what I've been trying. In here, I'm trying to get it to work for one table first, but I already got stuck here since it's not working.