Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

Saving Changes

Modifying entities is no more difficult than changing object states. The additional step is to perform the modifications and tell the Entity Framework to save the changes. Listing 2 selects customers with a CompanyName beginning with TEST, deletes the found objects from the NorthwindEntities class, and saves the changes.

Listing 2 Modifying data is a matter of changing object states (or removing objects) and telling the Entity Framework to save the changes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NorthwindModel;

namespace LinqToEntities
{
 class Program
 {
  static void Main(string[] args)
  {
   NorthwindEntities northwind = new NorthwindEntities();

   var customers = from customer in northwind.Customers
           where customer.CompanyName.StartsWith("TEST")
           select customer;

   Array.ForEach(customers.ToArray(), c => Console.WriteLine(c.CustomerID));

   Array.ForEach(customers.ToArray(), c => northwind.DeleteObject(c));
   northwind.SaveChanges();

   Console.ReadLine();

  }
 }
}

In Listing 2, Customers with a CompanyName starting with TEST are selected in the LINQ query. The CustomerIDs found are sent to the console. The Array.ForEach method is used to call DeleteObject on each found Customer and SaveChanges is called. That's it. Again, you don't have to even think about the logical database model or SQL. You focus on the conceptual model represented by your entities and LINQ, and the Entity Framework does the rest.

  • + Share This
  • 🔖 Save To Your Account