Limey
Limey

Reputation: 2772

linq to sql update standard

So I know there are many questions on how to update a DB with linq to SQL, my question is, am I doing this in an accepted standard?

here is my code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //load data to page
    }
    else
    {
        using (var db = new App_Data.MyDataContext())
        {
            var Query = (from p in db.peoples
                         where p.ipeople_ID == 59225
                         select p).Single();

            Query.cFirstName = FirstName.Value;

            try { db.SubmitChanges(); }
            catch (ChangeConflictException)
            {
                db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                db.SubmitChanges();
            }
        }
    }
}

I am learning asp.net by trial and error (and lots of google searches!) so i know it will work, just don't know if the code would get me laughed out of a conference! :D

Thanks

Upvotes: 5

Views: 754

Answers (2)

Bobby Borszich
Bobby Borszich

Reputation: 11767

Some changes:

I would move your logic away from the page load event, and explicitly trigger a save/update event.

I would address the change conflict if that is happening ... I wouldn't hide that error and attempt to resubmit changes.

protected void Page_Load(object sender, EventArgs e) {
 if (!IsPostBack){
  //load data to page
 }         
}

protected void SaveChanges_Click(object sender, EventArgs e) {
 using (var db = new App_Data.MyDataContext()) {
  var person = db.peoples.SingleOrDefault(p=> p.ipeople_ID == 59225);

  if(person == null) {
   // notify UI that person doesn't exist
   return;
  }

  person.cFirstName = txtFirstName.Text;

  try { db.SubmitChanges(); }
  catch (Exception ex){
   //Log error
  }
 }
}

Upvotes: 2

Hux
Hux

Reputation: 3122

This looks fairly standard to me, in it's approach. However I would suggest a different, simpler syntax for fetching single rows:

db.Peoples.SingleOrDefault(p => p.ipeople_ID == 59225)

This way, you will get NULL if the record doesn't exist. Single will throw an exception if no record is found. I would also separate the update code out into a button click at minimum, updating the person directly on Post back seems a little odd.

I also like lower-case variables for local variables, but I won't go into that.

Upvotes: 2

Related Questions