Delete query in Linq

I have this simple code, but it shows an error. I do not know where I am wrong. I am showing an error on the last line .. "DeleteOnSubmit" linq_testDataContext db = new linq_testDataContext ();

var remove = from aremove in db.logins where aremove.username == userNameString && aremove.Password == pwdString select aremove; db.logins.DeleteOnSubmit(remove); 
+6
c # linq linq-to-sql
source share
5 answers

you are missing a foreach loop to delete the whole entity.

Use as below

 var remove = from aremove in db.logins where aremove.username == userNameString && aremove.Password == pwdString select aremove; 

and after that

 foreach (var detail in remove) { db.logins.DeleteOnSubmit(detail); } 

and finally

  try { db.SubmitChanges(); } catch (Exception e) { // Provide for exceptions. } 

Hope this helps you.

+4
source share

DeleteOnSubmit accepts one object. You pass it an IEnumerable<login> . Use DeleteAllOnSubmit or select one object from your resulting collection, for example:

 var remove = (from aremove in db.logins where aremove.username == userNameString && aremove.Password == pwdString select aremove).FirstOrDefault(); if(remove != null) { db.logins.DeleteOnSubmit(remove); } 
+3
source share

Instead:

 db.logins.DeleteOnSubmit(remove); 

Call DeleteAllOnSubmit() , for example:

 db.logins.DeleteAllOnSubmit(remove.ToList()); 

After that, be sure to call db.SubmitChanges() . You can use .AsEnumerable() , either, or. If this is a big delete operation, you might consider going around LINQ in this case.

+2
source share

For good practices

  private void DeleteCourse() { int id = Convert.ToInt32( txtSearch.Text); CourseDemoDataContext cdContext = new CourseDemoDataContext(); course courseobj = cdContext.courses.Single(courses => courses.COURSE_ID == id); cdContext.courses.DeleteOnSubmit(courseobj); cdContext.SubmitChanges(); } 
0
source share

try using the first () method, something like this:

 var remove = (from aremove in db.logins where aremove.username == userNameString && aremove.Password == pwdString select aremove).first(); db.logins.DeleteOnSubmit(remove); 
0
source share

All Articles