Im trying to insert a list of players into a team, I have the list of players being sent to the controller and am picking them up, I then Create a new Team but when I go to add each player I get an error thrown saying: An exception of type 'System.NullReferenceException' occurred in EloraCurling.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
Here is the code for my ActionResult:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateLeagueTeam(ICollection<int> members)
{
Team team = new Team();
team.IsBonspiel = false;
team.IsLeague = true;
//sets the year the team is created
team.YearActive = games.getSeasonYear();
//finds and sets the league ID for the team
int leagueId = (int)Session["leagueId"];
League league = db.Leagues.Find(leagueId);
team.League = league;
//adds each member to the team
foreach (int memberId in members)
{
Member newMember = new Member();
newMember = db.Members.Find(memberId);
newMember.Teams.Add(team);
//team.Members.Add(newMember);
}
//gets the first member in the list and makes that member the skip
int skipId = members.First();
Member skip = db.Members.Find(skipId);
//assigns the member to the skip position and sets the team name
team.Skip = skip;
team.Name = skip.LastName;
if (ModelState.IsValid)
{
db.Teams.Add(team);
db.SaveChanges();
return RedirectToAction("Index");
}
}
The Member Model:
public class Member : Entity
{
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public DateTime? DateOfBirth { get; set; }
public ApplicationUser User { get; set; }
public bool HasSmartServe { get; set; }
public string SmartServeNumber { get; set; }
public bool IsActive { get; set; }
public bool IsEnabled { get; set; }
public string User_Id { get; set; }
public List<MembershipEntry> MembershipEntries { get; set; }
public List<Team> Teams { get; set; }
public List<League> Leagues { get; set; }
public List<Committee> Committees { get; set; }
}
I am getting the members and can see that it is an object but not sure why it will not add.