Hello
I’m following a tutorial which creates a winForm based app using C# and accessing SQL DBs and text files. Whilst I’m uncertain whether my problem is rooted on the SQL or C# side of the house I’m very strongly leaning towards C# despite the abort error message being an SQL exception provided by the Visual Studio debugger:
"System.Data.SqlClient.SqlException
Message=The INSERT statement conflicted with the FOREIGN KEY constraint "FK_TeamPlayers_Players". The conflict occurred in database "TourneyManagerSSMS", table "dbo.Players", column 'id_player'.
The statement has been terminated.
Source=.Net SqlClient Data Provider"
Table TeamPlayers is a junction table referencing /linked to the Team and Player parent tables via foreign keys.. According to what I could find searching the internet the above error occurs if either of the parent tables are empty or if the foreign key doesn’t exist in the linked parent table. Both parent tables have validated test data and the primary key of both is setup with IDENTITY (1,1). I can write to and read from the DB tables via winForms and the specific query being called in C# can be successfully executed in SSMS, populating the junction table with data.
The app aborts when attempting to INSERT to the junction table. Checking the value contained in “model.id” shows expected data. Checking the value contained in “addTM2db.id”, however, reveals a value of 0 – which of course does not exist in the Player parent table. Hovering the cursor over “model.TeamMembers” – which is where I think “addTM2db.id” is getting its content from – shows a numerical value consistent with the number of Players selected on the winForm dropdown to be attached to a given team.
I fail to understand why the values in “model.TeamMembers” are not being picked up by “addTM2db.id”.
Following is (I think) the relevant code:
public class Team
{
public int id { get; set; }
public string TeamName { get; set; }
public List<Player> TeamMembers { get; set; } = new List<Player>();
}
public class Player
{
public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EMail { get; set; }
public string CellPhone { get; set; }
public string getName { get { return $"{LastName}, {FirstName}"; } }
}
public partial class Create_Team : Form
{
// set-up for player combo dropdown and team Members listBox
private List<Player> availablePlayers = ConnectionConfig.Connects.GetPlayers_All();
private List<Player> selectedPlayers = new List<Player>();
private void nuTeamButton_Click(object sender, EventArgs e)
{
if (ValidateTeamInput())
{
MessageBox.Show("A Team Name must be entered.");
}
else
{
Team model = new Team();
{
model.TeamName = nuTeamNameTextBox.Text;
model.TeamMembers = selectedPlayers;
}
model = ConnectionConfig.Connects.nuTeam(model);
teamAdded();
// TODO MAYBE Re-Initialize Form
nuTeamNameTextBox.Text = "";
}
}
}
public class DatabaseConnect : IdataSourceConnect
{
private const string DB = "Tourneys_MS_SQL";
public Team nuTeam(Team model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionConfig.connectString(DB)))
{
var add2db = new DynamicParameters();
add2db.Add("@TeamName", model.TeamName);
add2db.Add("@id_team", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spTeams_ADD", add2db, commandType: CommandType.StoredProcedure);
model.id = add2db.Get<int>("@id_team");
foreach (Player addTM2db in model.TeamMembers) // values as expected
{
add2db = new DynamicParameters();
add2db.Add("@id_team", model.id); // values as expected
add2db.Add("@id_player", addTM2db.id); /// ====> ZERO !!!!!!!!!!!!!!!
// add2TMdb.Add("@id_teamplayers", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
/*====> ABORT LINE:*/ connection.Execute("dbo.spTeamPlayers_ADD", add2db, commandType: CommandType.StoredProcedure);
// model.id = add2TMdb.Get<int>("@id_teamplayers");
}
return model;
}
}
}
I’ve tried with and without the lines commented out (the tutorial author does it without) with the same SQL exception result. New teams are added to DB (line 54); run aborts on line 63.
Thank you in advance for your time & expertise.
Art