Update Single Column In Entity Framework

by Vahid 29. April 2011 18:00

I was working with Entity Framework and I needed to update a single column of a row in the database. basically I was logging the users visit to a web site (ASP.NET). so first time user lands in the website I create a record in database and keep the id in the session. when user’s session times out I needed to update the row and set the exit time of the user. it sounded a bit difficult to do this with Entity Framework I did it this way and worked pretty well:

        public void UpdateVisit(long id, string userId)
        {
            //id (row id) comes from the user so we create an object and assign the id
            VisitInformation visitInformation = new VisitInformation() { ID = id };
            try
            {
                using (var context = new TravIranLogEntities())
                {
                    //Here we attach the object to the context and set the state to unchanged
                    context.Entry(visitInformation).State = EntityState.Unchanged;
                    //update the column(s) that you need to modify
                    visitInformation.UserId = userId;
                    //Send the informatin back to the Database
                    context.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                LogManager.Log("Error in UpdateVisit for user id", ex, LogMode.LogAndEmai);
            }

        }

Tags: ,

.Net