我试图将一个玩家列表插入一个团队,我将玩家列表发送到控制器并正在接收它们,然后创建一个新团队但是当我去添加每个玩家时我得到一个错误扔了说: EloraCurling.dll中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理
附加信息:未将对象引用设置为对象的实例。
以下是我的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");
}
}
会员模型:
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; }
}
我正在获取成员,并且可以看到它是一个对象但不确定为什么它不会添加。
答案 0 :(得分:0)
这行是错误:
newMember.Teams.Add(team);
那是因为类型Teams
的{{1}}在使用前需要初始化,例如:
List<Team>
//现在在同一个循环中调用
newMember.Teams = new List<Team>();
这完全是基于对代码的快速审查,我对业务逻辑不太确定,你想要将已经创建的列表对象分配给newMember.Teams.Add(team);
,但这肯定需要先进行初始化可以调用newMember.Teams
方法添加另一个团队
答案 1 :(得分:0)
您未在Teams
初始化Member
媒体资源。只需为Member
添加默认构造函数,并将Teams
初始化为空List<Team>
:
public class Member : Entity
{
public void Member()
{
Teams = new List<Team>();
}
public List<Team> Teams { get; set; }