I've created a winform app that is using an EDM to populate the datagrids but on when trying to insert new records into this DGV I am getting this error: 'The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: The key-value pairs that define an EntityKey cannot be null or empty. Parameter name: record'
This does insert a record into the DB but CompanyID, ExecutiveID, and ExecutiveType are all set to 0 which is not correct.
So I would like to populate CompanyID, ExecutiveID, and ExecutiveType with the selected dropdown value before saving my entity changes. Can anyone help me retrieve these values and assign them to the entity property?
I'm populating a datagrid with this code:
private void frmCompanyExecutives_Load(object sender, EventArgs e)
{
dal = new DataAccessLayer();
try
{
this.dgvCompanyExecutives.DataSource = dal.GetCompanyExecutivesList();
dgvCompanyExecutives.Columns["CompanyName"].Visible = false;
dgvCompanyExecutives.Columns["ExecutiveName"].Visible = false;
List<Companies> companies = dal.GetCompanyList1();
List<Executives> executive = dal.GetExecutivesList1();
foreach (DataGridViewRow row in dgvCompanyExecutives.Rows)
{
DataGridViewComboBoxCell rowCompanyCombocell = (DataGridViewComboBoxCell)row.Cells["CompanyName1"];
rowCompanyCombocell.DataSource = companies;
rowCompanyCombocell.DisplayMember = "CompanyName";
rowCompanyCombocell.ValueMember = "CompanyID";
rowCompanyCombocell.Value = row.Cells["CompanyID"].Value;
DataGridViewComboBoxCell rowExecutiveCombocell = (DataGridViewComboBoxCell)row.Cells["ExecutiveName1"];
rowExecutiveCombocell.DataSource = executive;
rowExecutiveCombocell.DisplayMember = "ExecutiveName";
rowExecutiveCombocell.ValueMember = "ExecutiveID";
rowExecutiveCombocell.Value = row.Cells["ExecutiveID"].Value;
DataGridViewComboBoxCell rowExecTypeCombocell = (DataGridViewComboBoxCell)row.Cells["ExecutiveType"];
int ExecutiveTypeID = Convert.ToInt32(row.Cells["ExecutiveTypeID"].Value);
if (ExecutiveTypeID == 1)
rowExecTypeCombocell.Value = "Director";
else
rowExecTypeCombocell.Value = "Secretary";
}
dgvCompanyExecutives.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dgvCompanyExecutives.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Exception occurred: {0}", ex.Message));
}
}
On my btnSave click event I need some code to capture these values
private void btnSave_Click(object sender, EventArgs e)
{
try
{
dal.entities.SaveChanges();
MessageBox.Show("Changes saved to the database.");
this.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}