在我的数据库中,我有 2 个表 Employee 和 Address。在表单中,单个选项卡代表两个表的字段。在确定按钮的单击事件下,我尝试插入数据但发生异常。我能够一次插入一个表的数据,但不能同时插入两个表。
我有例外:
“ObjectStateManager中已经存在具有相同键的对象。现有对象处于Modified状态。只有处于Added状态的对象才能添加到ObjectStateManager。”
我的代码是:
try
{
using (TransactionScope ts = new TransactionScope())
{
db.Connection.Open();
string empid = txtEmpId.Text.ToString();
Employee emp = db.Employees.Single(a => a.Emp_ID == empid);
emp.Full_Name = txtFullName.Text;
db.AddToEmployees(emp);
db.SaveChanges();
Address address = db.Addresses.Single(b => b.Emp_Id == empid);
address.House_No = txtHouseNo.Text.ToString();
db.AddToAddresses(address);
db.SaveChanges();
ts.Complete();
MessageBox.Show("completed successfully");
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
finally
{
if (db.Connection.State == ConnectionState.Open)
{
db.Connection.Close();
}
}
请帮助我!