[英]Insertion of data in two different tables using Entity Framework within single Button click in c#
In my database I've 2 tables Employee and Address. 在我的数据库中,我有2个表Employee和Address。 In forms a single tab represents the fields of both tables.
在表单中,单个选项卡代表两个表的字段。 Under the click event of OK button i tried to insert the data but Exception occurred.
在“确定”按钮的单击事件下,我尝试插入数据,但发生异常。 I'am able to insert the data one table at a time but not both.
我能够一次将数据插入一个表,但不能同时插入两个表。
I'm having exception: 我有例外:
"an object with the same key already exists in ObjectStateManager. The existing object is in Modified state. An object can only be added to the ObjectStateManager if it is in the Added State." “ ObjectStateManager中已经存在具有相同键的对象。现有对象处于修改状态。如果对象处于添加状态,则只能将其添加到ObjectStateManager。”
My code is: 我的代码是:
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();
}
}
Pl z help me out! 请帮我!
By the looks of your posted code, you retrieve an address from the database, update it, but then try to add it back into the database? 根据您发布的代码的外观,您从数据库中检索了一个地址,对其进行了更新,然后尝试将其重新添加到数据库中?
This causes a primary key conflict since the record cannot be inserted twice. 由于记录不能插入两次,因此会导致主键冲突。
Remove the line which adds the address to the database, since it is already in there. 删除将地址添加到数据库的行,因为它已经在数据库中了。
You can Use Transactions for inserting into the two tables as one SQL statement 您可以使用事务作为一个SQL语句插入到两个表中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.