public ActionResult Create(MatchMiddleStage matchmiddlestage)
 {
     var matchError = GetMatchError(matchmiddlestage);
     if (ModelState.IsValid && string.IsNullOrEmpty(matchError)) {
         _db.MatchesMiddleStage.Add(matchmiddlestage);
         _db.SaveChanges();
         return RedirectToAction("Index");
     }
     ViewBag.HomeTeamId = new SelectList(_db.Teams, "Id", "Name", matchmiddlestage.HomeTeamId);
     ViewBag.AwayTeamId = new SelectList(_db.Teams, "Id", "Name", matchmiddlestage.AwayTeamId);
     ViewBag.Error = matchError;
     return View(matchmiddlestage);
 }
 public ActionResult Edit(MatchMiddleStage matchmiddlestage)
 {
     if (ModelState.IsValid) {
         _db.Entry(matchmiddlestage).State = EntityState.Modified;
         _db.SaveChanges();
         return RedirectToAction("Mellomspill", "Home");
     }
     ViewBag.HomeTeamId = new SelectList(_db.Teams, "Id", "Name", matchmiddlestage.HomeTeamId);
     ViewBag.AwayTeamId = new SelectList(_db.Teams, "Id", "Name", matchmiddlestage.AwayTeamId);
     return View(matchmiddlestage);
 }
 private string GetMatchError(MatchMiddleStage matchmiddlestage)
 {
     var homeTeam = _db.Teams.Find(matchmiddlestage.HomeTeamId);
     var awayTeam = _db.Teams.Find(matchmiddlestage.AwayTeamId);
     var isInSameGroup = homeTeam.GroupMiddleStageId == awayTeam.GroupMiddleStageId;
     var homeTeamOpponents =
         homeTeam.HomeMatchesMiddleStage.Select(x => x.AwayTeamId).Concat(
             homeTeam.AwayMatchesMiddleStage.Select(x => x.HomeTeamId)).Distinct();
     var hasNotPlayedBefore = !homeTeamOpponents.Contains(awayTeam.Id);
     var error = isInSameGroup ? string.Empty : "Ikke i samme gruppe";
     error += hasNotPlayedBefore ? string.Empty : "Kamp allerede registrert";
     error += matchmiddlestage.HomeTeamId != matchmiddlestage.AwayTeamId ? string.Empty : "Samme lag";
     return error;
 }