Click here to Skip to main content
14,697,740 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
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
    {
	// Get the List of CompanyExecutives from the DAL and bind to Datagrid 
	this.dgvCompanyExecutives.DataSource = dal.GetCompanyExecutivesList();
	dgvCompanyExecutives.Columns["CompanyName"].Visible = false;
	dgvCompanyExecutives.Columns["ExecutiveName"].Visible = false;
	// Get the List of Companies/Executives from the DAL and bind to Datagrid Dropdown columns
	List<Companies> companies = dal.GetCompanyList1();
	List<Executives> executive = dal.GetExecutivesList1();
				
        //Read each row in the Grid and determine what the ExecutiveType DropDown should be set to based on the ExecutiveTypeID 
	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;
	    	
	    //set ID to value(1 or 2) from ExecutiveTypeID cell for that row
	    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
  {
    //Save object changes to the database, display a message, and refresh the form.
    dal.entities.SaveChanges();
    MessageBox.Show("Changes saved to the database.");
    this.Refresh();
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}
Posted

1 solution

When visual studio's wizard drop your view in your model, it add a StoreGeneratedPattern="Identity" on some properties (probably the keys of your entity).

When generating requests on a regular table, this property tells entity framework to expect an ID in return, so it append a select scope_identity() at the end of the insert.

Now with updatable views the scope_identity is screwed because the insert happen in another scope and it returns null, so the insert fail.

If you remove this StoreGeneratedPattern="Identity" from the model, entity framework doesn't append select scope_identity() and the insert is working fine.

I hope this solve your problem.
   
Comments
pmcm 12-Mar-12 11:24am
   
DO i remove this StoreGeneratedPattern="Identity" from all of my entities? The enitiy I'm having trouble updating is from a view and the XML is this:
<entitytype name="tbl_CompanyExecutives">
<key>
<PropertyRef Name="CompanyID" />
<PropertyRef Name="ExecutiveID" />
<PropertyRef Name="ExecutiveType" />

<Property Name="CompanyID" Type="int" Nullable="false" />
<Property Name="ExecutiveID" Type="int" Nullable="false" />
<Property Name="ExecutiveType" Type="int" Nullable="false" />
<Property Name="DateAppointment" Type="datetime" />
<Property Name="DateResignation" Type="datetime" />
pmcm 12-Mar-12 11:46am
   
I have tried what you suggested but I am still getting the same problem.
<!--Errors Found During Generation: warning 6002: The table/view CompanySecretarial_Datawarehouse.dbo.vw_CompanyExecutives' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.-->
<entitytype name="vw_CompanyExecutives">
<key>
<PropertyRef Name="CompanyExecutiveID" />

<Property Name="CompanyName" Type="nvarchar" Nullable="false" MaxLength="255" />
<Property Name="ExecutiveName" Type="nvarchar" Nullable="false" MaxLength="255" />
<Property Name="ExecutiveType" Type="int" Nullable="false" />
<Property Name="DateAppointment" Type="datetime" />
<Property Name="DateResignation" Type="datetime" />
<Property Name="CompanyID" Type="int" Nullable="false" />
<Property Name="ExecutiveID" Type="int" Nullable="false" />
<Property Name="CompanyExecutiveID" Type="int" Nullable="false" />


and the same in the CSDL Content Section
<entitytype name="vw_CompanyExecutives">
<key>
<PropertyRef Name="CompanyExecutiveID" />

<Property Type="String" Name="CompanyName" Nullable="false" MaxLength="255" FixedLength="false" Unicode="true" />
<Property Type="String" Name="ExecutiveName" Nullable="false" MaxLength="255" FixedLength="false" Unicode="true" />
<Property Type="Int32" Name="ExecutiveType" Nullable="false" />
<Property Type="DateTime" Name="DateAppointment" />
<Property Type="DateTime" Name="DateResignation" />
<navigationproperty name="Executives" relationship="CompanySecretarialDatawarehouse.vw_CompanyExecutivesExecutives" fromrole="vw_CompanyExecutives" torole="Executives">
<Property Type="Int32" Name="CompanyID" Nullable="false" />
<Property Type="Int32" Name="ExecutiveID" Nullable="false" />
<navigationproperty name="Company" relationship="CompanySecretarialDatawarehouse.Companiesvw_CompanyExecutives" fromrole="vw_CompanyExecutives" torole="Companies">
<Property Type="Int32" Name="CompanyExecutiveID" Nullable="false" />

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900