I'm new to entity framework core. I'm trying to save data in a team and player tables, but I get a
Object reference not set to an instance of an object
error. Here is my sample code below:
Player Class
public class Player
{
public int PlayerID {get;set;}
public string PlayerName {get;set;}
public int TeamID {get;set;}
public Team Team {get; set;}
}
Team class
public class Team
{
public int TeamId {get;set;}
public string TeamName {get;set;}
public ICollection<Player> Players {get;set;}
}
DBContext
public class SoccerDbContext: DbContext
{
public SoccerDbContext(DbContextOptions<SoccerDbContext> options):base(options)
{}
public DBSet<Team> Teams {get;set;}
public DBSet<Player> Players {get;set;}
}
Controller post method
[HttpPost]
public async Task<ActionResult> Save(Team team)
{
Player player1 = new Player{
PlayerName = "Steven"
};
Player player2 = new Player{
PlayerName = "Frank"
};
team.Players.Add(player1); //This I where the error occurs
team.Players.Add(player2);
_context.Team.Add(team);
await _context.SaveChangesAsync();
return RedirectToAction("index");
}
Whenever I execute this code I receive "Object reference not set to an instance of an object" any idea? Thank you Error image
The error is occuring as the Players
collection is null. You can instantiate by default as follows:
public class Team
{
public int TeamId {get;set;}
public string TeamName {get;set;}
public ICollection<Player> Players {get;set;} = new HashSet<Player>();
}
Did you set your constructor in the class?
public Player(string name)
{
PlayerName = name;
}
That way you can create a new instance like this
Player player1 = new Player("Steven")
Player player2 = new Player("Frank")
In your Team
object, you never initialize the Players collection. Therefore, team.Players
is null when you call the Add()
method.
You can initialize the property like so:
public ICollection<Player> Players {get;} = new List<Player>();
Your Players
property is null
,
You can create it before you add
team.Players = new List<Player>();
team.Players.Add(player1);
team.Players.Add(player2);
but i guess you want to add new team from somewhere so you should send the Players
inside you http request as you do with the team, for example
{
"teamName": "MyTeam",
"players": [
{
"playerName": "Steven"
},
{
"playerName": "Frank"
}
]
}
Your players don't exist in the database and wont have an id until you save them before you add to your team.players list. Perhaps try
_context.Players.add(player1);
_context.Players.add(player2);
_context.SaveChanges();
team.Players.Add(player1); //This I where the error occurs
team.Players.Add(player2);
_context.Team.Add(team);
await _context.SaveChangesAsync();
tbh im sure theres a more efficient way but this is a way around at least also yes you should initialise your list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.