« Perfect reference to get started with EntityFramework 4.1 | Why I believe software development should be like amazon kindle development »

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);
            }

        }

.Net

Comments (0)

Related posts

Entity Framework learning resouce browsing internet i found this document about ado.net entity framework which comes with microsoft …Perfect reference to get started with EntityFramework 4.1Just found these set of post in the MSDN site for getting started with EntityFramework 4.1. if you a…Customizing Entity Framework Classes in VS 2010  need to know about new cool features in visual studio 2010? check this link which describes …

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen