朋友。 我真的需要你的帮助。我会很感激。错误“一个实体对象不能被多个IEntityChangeTracker实例引用”
所以我在MS SQL Server中有实体“模型”c字段“ID_model”和“名称”。 我想要在Form1上单击“编辑”后,还有另一种形式(FormModel),您可以在其中更改数据并将更改写入数据库。
问题是,按下“编辑”后有一个关于“其他信息:一个实体对象不能被多个IEntityChangeTracker实例引用”的错误,我不知道如何解决它。从Form1中
代码:
从FormModelpublic partial class Form1 : Form
{
MyDBEntities db2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
db2 = new MyDBEntities();
modelBindingSource.DataSource = db2.Models.ToList();
dataGridView.Columns.RemoveAt(2);
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (modelBindingSource.Current == null)
return;
using (FormModel frm = new FormModel(modelBindingSource.Current as Model))
{
if (frm.ShowDialog() == DialogResult.OK)
{
modelBindingSource.DataSource = db2.Models.ToList();
}
}
}
}
代码:
public partial class FormModel : Form
{
MyDBEntities db2;
public FormModel(Model obj)
{
InitializeComponent();
db2 = new MyDBEntities();
if (obj == null)
{
modelBindingSource.DataSource = new Model();
db2.Models.Add(modelBindingSource.Current as Model);
}
else
{
modelBindingSource.DataSource = obj;
db2.Models.Attach(modelBindingSource.Current as Model);
}
}
private void FormModel_FormClosing(object sender, FormClosingEventArgs e)
{
if (DialogResult == DialogResult.OK)
{
if (string.IsNullOrEmpty(txtModelName.Text))
{
MessageBox.Show("There are empty fields", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtModelName.Focus();
e.Cancel = true;
return;
}
db2.SaveChanges();
e.Cancel = false;
}
e.Cancel = false;
}
}
我真的希望帮助。祝一切顺利。请原谅我的英语。
您正在将相同的项目附加到多于1个上下文,这是不允许的。这是你如何得到错误。请参阅[this](http://stackoverflow.com/questions/10191734/entity-object-cannot-be-referenced-by-multiple-instances-of-ientitychangetracker)以获取更多信息。 – CodingYoshi
感谢您的回复。但我不知道如何解决这个问题。我看了你的链接,但它没有帮助我。 –