Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 825
Limey Avatar asked Oct 11 '22 15:10

Limey


1 Answers

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
  }
 }
}
like image 138
Bobby Borszich Avatar answered Oct 19 '22 01:10

Bobby Borszich