entity framework - save changes to entities


To save the changes made to the entities to a database, we need to call the ObjectContext class SaveChanges method. In the example given below, the query retrieves the first customer from the entityset -Customer.

The context.Customer returns the Objectset of Customer types and the LINQ extension method First()returns only the first customer.

We can edit the first customer details like name and address by assigning new values to the properties and call the SaveChanges() method to save the changes back to the database.

During SaveChanges, the ObjectContext determines which fields were changed. In this example, only name and address are changed. So, only those two values are sent into the command. To identify the row to be updated in the database, the ObjectContext uses the value of the EntityKey property.

using (var context = new SalesOrderManagementEntities())
{
	var Customer = context.Customer.First();
	Customer.Name = "BHA";
	Customer.Address = "address1";
	context.SaveChanges();
	//The below query is for displaying the customer details after edit operation
	var query = from c in context.Customer
		select c;
	foreach (var c in query)
	{
		Console.WriteLine(String.Format("{0} {1}",
				c.Name, c.Address));
	}
	Console.WriteLine();
	Console.ReadLine();
}