如何更新现有的LINQ实体?
这段代码告诉我:“无法插入已存在的实体。”
有关使用linq更新/插入的更好的做法吗?
foreach (ListViewItem lvi in lvStudents.Items)
{
HiddenField hfStudentID = lvi.FindControl("hfID") as HiddenField;
CheckBox cbPresent = lvi.FindControl("mycb") as CheckBox;
int sInt = Int32.Parse(hfStudentID.Value);
dc = new DataClassesSODataContext();//I renewed the dc to make sure that wasn't the problem?
var currStudent = dc.students.Single(x => x.studentID == sInt);
grade g = dc.grades.Single(x => x.subjectID == subjID || x.studentID == sInt);
if (g == null)
{
g = new grade();
g.subject = dc.subjects.Single(x => x.subjectID == subjID);
g.student = currStudent;
g.present = cbPresent.Checked;
dc.grades.InsertOnSubmit(g);
} else
{
g.present = cbPresent.Checked;
dc.grades.Attach(g, true);//I tried both attaching and inserting
}
}
dc.SubmitChanges();
答案 0 :(得分:0)
您只需设置现有实体的值,然后调用submitchanges。类似的东西:
var g=dc.grades.Single(x => x.subjectID == subjID || x.studentID == sInt);
g.subject="some new subject";
dc.SubmitChanges();
Insert仅用于添加新实体,attach用于将实体从另一个DataContext附加到现有上下文。