Update in Entity Framework

Hi friends,

In the previous post, we saw about insert, delete and displaying records using Entity Framework. This week let us see how to update a record in Entity framework.

In order to perform update we need to, 1) Fetch the object using a LINQ, 2) Assign the values to be updated, 3) Save the changes to persist the values in db.


using (SampleDatabaseEntities context = new SampleDatabaseEntities())
{
int i = 1;
Dictionary recordDict = new Dictionary();
var CountryTable = from offices in context.Offices
join countries in context.Countries on offices.CountryId equals countries.Id
select new
{
CountryName = countries.Name,
Location = offices.Name
};
foreach (var ent in CountryTable.ToList())
{
Console.WriteLine(i + ")\t" + ent.CountryName + "-----" + ent.Location);
recordDict[i] = ent.CountryName + "-" + ent.Location;
i++;
}
Console.WriteLine("Enter the element to be updated from the choices 1 to {0}", i);
int c = Int32.Parse(Console.ReadLine());
if (c < i)
{
string country = recordDict[c].Split('-').ElementAt(0);
string location = recordDict[c].Split('-').ElementAt(1);
Office obj = (from ent in context.Offices
join con in context.Countries on ent.CountryId equals con.Id
where con.Name == country && ent.Name == location
select ent).FirstOrDefault(); //Fetch the record using the framework's class object
Console.WriteLine("Enter the new name to be updated instead of {0}", obj.Name);
obj.Name = Console.ReadLine(); //Update the record by assigning the value to the desired property
context.SaveChanges(); //Save the changes in the database
}
else
{
Console.WriteLine("Invalid Choice");
}

Whenever we perform updation inside the loops/while writing batch updation logics, it is recommended to use “context.ObjectStateManager.ChangeObjectState(obj, EntityState.Modified);” to perform updates.

int i=1;
foreach(var obj in ListElements)
{
obj.CountryID = i;
context.ObjectStateManager.ChangeObjectState(obj, EntityState.Modified); //requires namespace using System.Data.Objects; and using System.Data;
context.SaveChanges();
i++;
}

Hope it helps. Happy Learning!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s