Retrieve and update record with Entity Framework in web app

asp.net c# entity-framework linq-to-entities

Question

I am new to development and trying to retrieve a record to display and edit in a FormView on an ASP.NET web app page, using Entity Framework 5.0 (database first method), but I am not sure of the best way to go about this.

To retrieve the record, I use the following code:

protected void Page_Load(object sender, EventArgs e)
{
    LoadData(int.Parse(Session["PersonID"].ToString()));
}

private void LoadData(int iPersonID)
{
    using (PeopleEntities ctx = new PeopleEntities())
    {
        var query = (from a in ctx.People
                     where a.PersonID == iPersonID
                     select a).FirstOrDefault();

        TextBoxFirstName.Text = query.FirstName;
        TextBoxLastName.Text = query.LastName;
    }
}

And to save it, I use:

protected void ButtonSave_Click(object sender, EventArgs e)
{
    SaveEmployee(int.Parse(Session["PersonID"].ToString()));
}

private void SaveEmployee(int iPersonID = 0)
{
    using (PeopleEntities ctx = new PeopleEntities())
    {  
        var query = (from a in ctx.People
                     where a.PersonID == iPersonID
                     select a).FirstOrDefault();

        query.FirstName = TextBoxFirstName.Text;
        query.LastName = TextBoxLastName.Text;
        ctx.SaveChanges();
    }
}

It seems silly to me to have these two methods each query the database to retrieve and update the record, but, again, I am a novice, and maybe I'm just missing something. Is there a way to populate the controls on the FormView with the entity and have a method to save the record without having to manually assign the values (query.FirstName = TextBoxFirstName.Text, etc.) based on state?

I have seen the EntityDataSource, but I do not think that will be a good option for anything but the simplest of things.

Can anyone please tell me if what I am doing is ok or provide a better example or guidance?

Your help is greatly appreciated!

1
0
9/26/2013 11:13:27 PM

Popular Answer

Best approach, IMHO, is that when you're retrieving data to DISPLAY only, do it without change-tracking. This will avoid performance issues. So, use the AsNoTracking method to avoid change-tracking proxies.

Than, for the update, you should load WITH change-tracking enabled, that's why there is no call to AsNoTracking on the save part.

Remember to check for null values. You're using the FirstOrDefault but since you're using the primary key, there won't be a second record, so just using SingleOrDefault. But since default (null) can happen, check for null values.

Also, use lambda expressions. They are not so easy to get with at first but you'll get used with minor effort and they will simplify your code a lot.

But from your question, there are some workarounds to avoid this but they are not the best approach. You should avoid long-living entities and prefer ViewModels for long-living objects, with the UnitOfWork pattern in mind for the repository and persistent entities.

If you really want that, you can Detach your entity from the context, use it everywhere and when you're ready, Attach it back and set it's state to Modified. For this, take a look here: http://msdn.microsoft.com/en-us/library/bb896271.aspx

On your case, I'd suggest this:

private void LoadData(int iPersonID)
{
   using (PeopleEntities ctx = new PeopleEntities())
   {
      // AsNoTracking will avoid performance hit of change-tracking here...
      // Since we're building-up a view, not an update case yet, you don't have to create
      // proxies that will check for entity changing...
      var query = ctx.People.AsNoTracking().SingleOrDefault(_people => _people.PersonID == iPersonID)

      // Rendering comes into action
      if (query != null)
      {
         TextBoxFirstName.Text = query.FirstName;
         TextBoxLastName.Text = query.LastName;
      }
   }
}

private void SaveEmployee(int iPersonID = 0)
{
   using (PeopleEntities ctx = new PeopleEntities())
   {  
      var query = ctx.Prople.SingleOrDefault(_person => _person.PersonID == iPersonID);

      if (query != null)
      {
         query.FirstName = TextBoxFirstName.Text;
         query.LastName = TextBoxLastName.Text;
         ctx.SaveChanges();
      }
   }
}
1
9/26/2013 11:53:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow