0

I made a database of a school which contains a bunch of values and I'm trying to make an update function in the program I'm making , whenever I save the changes in the server it gives an Exception, here is a code sample of which how I update the row locally:

var query =
    from s in db.Students
    where s.StudentID == querierID
    select s;

foreach (Student s in query)
{
    s.FirstName = fntb.Text;
    s.LastName = lntb.Text;
    s.Mobile = mobiletb.Text;
    s.Street = streettb.Text;
}

And here is how I Actually save to the database(Send the updated row to it)

db.SaveChanges();
Volkan Paksoy
  • 6,727
  • 5
  • 29
  • 40
GamerGamesGames
  • 71
  • 1
  • 10

2 Answers2

1

If StudentID is the primary key, you should write your code in a way that it will fail if this logic becomes false.

By using the Single() extension method your code will return just a single student or throw if the query returns more results.

This makes your code more readable

var studentToEdit = (
    from s in db.Students
    where s.StudentID == querierID
    select s
    ).Single();

studentToEdit.FirstName = fntb.Text;
studentToEdit.LastName = lntb.Text;
studentToEdit.Mobile = mobiletb.Text;
studentToEdit.Street = streettb.Text;

db.SaveChanges();

If you had used this approach, you would gotten a more detailed exception, pointing you in the right direction immedialtely.

Writing exactly what you mean, is the most difficult part of programming but has big advantages, like this.

Ric .Net
  • 5,540
  • 1
  • 20
  • 39
0

Okay , so I found the answer to it , the problem isn't actually what i thought it was , it is that when I Signed QueryID it was like

Selectedstudent.StudentID = QueryID

Instead of

QueryID = Selectedstudent.StudentID

I'm really sorry for wasting everyones time , but thank you all for trying to help me. and if anyone has a problem , they better check their code before posting a question and wasting everyones time like I did , really sorry everyone :( .

GamerGamesGames
  • 71
  • 1
  • 10