在DataGridView nd更新数据库中插入新行 [英] Inserting new row into DataGridView nd Updating DB

查看:147
本文介绍了在DataGridView nd更新数据库中插入新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Winform应用程序,该应用程序使用EDM填充数据网格,但是在尝试将新记录插入此DGV时,出现了以下错误:"对数据库的更改已成功提交,但是更新对象上下文时发生错误. ObjectContext可能处于不一致状态.内部异常消息:定义EntityKey的键值对不能为null或为空.参数名称:记录"
这确实将记录插入到数据库中,但是CompanyID,ExecutiveID和ExecutiveType都设置为0,这是不正确的.

因此,在保存我的实体更改之前,我想用选定的下拉值填充CompanyID,ExecutiveID和ExecutiveType.任何人都可以帮助我检索这些值并将其分配给实体属性吗?

我使用以下代码填充数据网格:

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));
  }
}



在我的btnSave click事件上,我需要一些代码来捕获这些值



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);
  }
}

推荐答案

当Visual Studio向导将您的视图放到模型中时,它会在其中添加StoreGeneratedPattern ="Identity"在某些属性上(可能是您实体的键).

在常规表上生成请求时,此属性告诉实体框架期望返回ID,因此它将在插入的末尾附加一个select scope_identity().

现在有了可更新的视图,因为插入发生在另一个作用域中并且返回了null,所以scope_identity搞砸了,因此插入失败.

如果您删除此StoreGeneratedPattern ="Identity",从模型中,实体框架不会追加select scope_identity()并且插入工作正常.

我希望这能解决您的问题.
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.


这篇关于在DataGridView nd更新数据库中插入新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆