Reputation: 65
I'm trying to add a player in the table that doesn't have a team and I'm getting the following exception :
INSERT statement conflicted with the FOREIGN KEY constraint The conflict occurred in database.
This is my playerModel, I have foreign key id_team that is nullable and yet when I am trying to add a player I get this error.
public class PlayerModel
{
public int id_player { get; set; }
public string player_surname { get; set; }
public string player_firstname { get; set; }
public int player_skill { get; set; }
public int? id_team { get; set; }
public string name_team { get; set; }
public int player_value { get; set; }
}
I put a breakpoint and when is trying to save in database is getting exception
public bool CreateNewPlayer(PlayerModel newPlayer)
{
if (newPlayer == null)
{
return false;
}
if (newPlayer.player_surname==null)
{
return false;
}
if (newPlayer.player_firstname==null)
{
return false;
}
var newDBPlayer = mappingService.MapPlayerFromForm(newPlayer);
dbContext.players.Add(newDBPlayer);
try
{
dbContext.SaveChanges();
}
catch (Exception ex)
{
return false;
}
return true;
}
here I mapped the player model for database model
public players MapPlayerFromForm(PlayerModel formPlayer)
{
var toRet = new players
{
player_firstname=formPlayer.player_firstname,
player_surname=formPlayer.player_surname,
player_skill=formPlayer.player_skill,
id_team=formPlayer.id_team,
player_value=formPlayer.player_value
};
return toRet;
}
I'm using jquery to add player into database. How can I solve this problem ?
Upvotes: 1
Views: 581
Reputation: 18749
In your MapPlayerFromForm
, check the value of formPlayer.id_team
and if it's 0, then set the value to NULL
. Also, set the id_team
property in players
to a nullable int
, or it will take a default value of 0.
public class players //consider calling this Player
{
public int? id_team {get;set;}
}
In the method...
id_team=formPlayer.id_team == 0 ? null : formPlayer.id_team,
See ? Operator
on msdn.
Upvotes: 1