views:

22

answers:

1

How can I update an existing LINQ entity?
This code gives me: "Cannot insert an entity that already exists."
Any better practises on updating/inserting with 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();
A: 

You simply need to set the existing entity's values and then call submitchanges. Something like:

var g=dc.grades.Single(x => x.subjectID == subjID || x.studentID == sInt);
g.subject="some new subject";
dc.SubmitChanges();

Insert is just for adding new entities and attach is for attaching entities from another DataContext to your existing context.

Adrian Grigore
Omg, I missed that. Thanks!
kversch
Just a word of advice though since you are just starting out with linq-to-sql: Have a look at Entity Framework instead. Essentially it does the same as Linq To SQL (plus a lot more), but it's still going to be supported by MS whereas LinqToSql is more or less dead.
Adrian Grigore