我正在使用 LINQ 语句更新数据库中的数据。首先用户将搜索姓名,详细信息将显示在 gridview 中,然后用户将选择一名员工,数据将显示在相关文本框和下拉列表中。
当我在两个下拉列表中选择数据时,它工作正常并且数据库得到更新,如果我只选择一个下拉列表,它显示错误
"The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Emp_Location". The conflict occurred in database "EmpDept", table "dbo.Location", column 'LocationID'."
//更新按钮
using (DataClassesDataContext dc = new DataClassesDataContext())
{
Emp employee = dc.Emps.Single(emp => emp.EmpID == id);
employee.EmpFirstName = txtFirstName.Text;
employee.EmpLastName = txtLastName.Text;
employee.MgrID = int.Parse(txtMgrID.Text);
employee.BirthDate = Convert.ToDateTime(txtDOB.Text);
employee.Email = txtEmail.Text;
employee.Mobile = txtMobile.Text;
employee.LocationID = ddlLocation.SelectedIndex;
employee.Salary = int.Parse(txtSalary.Text);
employee.DeptID = ddlDepartment.SelectedIndex;
//dc.Emps.InsertOnSubmit(employee);
dc.SubmitChanges();
ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Record Updated Successfully!!!')", true);
clearFields();
}
// GridView
protected void gvSearch_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
ddlDepartment.Items.RemoveAt(0);
ddlLocation.Items.RemoveAt(0);
string ddlDept = gvSearch.SelectedRow.Cells[9].Text;
string ddlLoc = gvSearch.SelectedRow.Cells[10].Text;
ListItem deptRemove = ddlDepartment.Items.FindByText(ddlDept);
ddlDepartment.Items.Remove(deptRemove);
ListItem locRemove = ddlLocation.Items.FindByText(ddlLoc);
ddlLocation.Items.Remove(locRemove);
txtEmpID.Text = gvSearch.SelectedRow.Cells[1].Text;
txtFirstName.Text = gvSearch.SelectedRow.Cells[2].Text;
txtLastName.Text = gvSearch.SelectedRow.Cells[3].Text;
txtMgrID.Text = gvSearch.SelectedRow.Cells[4].Text;
txtDOB.Text = gvSearch.SelectedRow.Cells[5].Text;
txtEmail.Text = gvSearch.SelectedRow.Cells[6].Text;
txtMobile.Text = gvSearch.SelectedRow.Cells[7].Text;
txtSalary.Text = gvSearch.SelectedRow.Cells[8].Text;
ddlDepartment.Items.Insert(0, new ListItem(ddlDept));
ddlLocation.Items.Insert(0, new ListItem(ddlLoc));
}
catch
{
}
}
//下拉列表
private void BindDDL()
{
try
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var location = from l in dc.Locations
select l;
ddlLocation.DataSource = location;
ddlLocation.DataValueField = "LocationID";
ddlLocation.DataTextField = "LocationName";
ddlLocation.DataBind();
ddlLocation.Items.Insert(0, new ListItem("--Select Location--"));
var department = from d in dc.Depts
select d;
ddlDepartment.DataSource = department;
ddlDepartment.DataValueField = "DeptID";
ddlDepartment.DataTextField = "DeptName";
ddlDepartment.DataBind();
ddlDepartment.Items.Insert(0, new ListItem("--Select Department--"));
}
}
最佳答案
您已经使用了 SelectedIndex
,而是使用 SelectedValue
:
employee.LocationID = int.Parse(ddlLocation.SelectedValue);
同样适用于部门:
employee.DeptID = int.Parse(ddlDepartment.SelectedValue);
您很幸运,没有与 selected-index 匹配的 ID,因此您得到了这个错误而不是不一致。外键约束有用的另一个原因。
关于c# - 我正在使用 linq 语句更新数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31340687/