Using the Entity Framework: Update Operation (Quick Reference)

How to Use the Entity Framework to Update Records in a Relational Database

This quick reference is for those who are using the Entity Framework and want examples of how to perform everyday CRUD tasks. We’ll take a look at how to update objects and associated objects using the Entity Framework.

Quick Reference Setup

Entity Framework & Linq to Entities: “Movies” Example Setup contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.

Update a Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d => d.Name == "Spike Jonze").First();

     spikeJonze.Name = "Adam Spiegel a.k.a \"Spike Jonze\"";
     _entities.SaveChanges();

     Console.ReadLine();
}

First, we retrieve a Director object by specifying a value for the Name property in a lambda expression. Next, we update the Director’s Name property. Finally, we call the ObjectContext’s SaveChanges method to commit the changes to the model and the database.

Using the ObjectStateManager when Updating a Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d => d.Name == "Spike Jonze").First();

     spikeJonze.Name = "Adam Spiegel a.k.a \"Spike Jonze\"";

     ObjectStateEntry entry = _entities.ObjectStateManager.
               GetObjectStateEntry(spikeJonze.EntityKey);
     IEnumerable<string$gt; modProps = entry.
               GetModifiedProperties();

     foreach (string prop in modProps)
     {
          Console.WriteLine("Modified Property: {0}", 
                    prop.ToString());

          Console.WriteLine("IsDbNull: {0}", 
                    entry.OriginalValues.
                    IsDBNull(
                         entry.OriginalValues.GetOrdinal(prop)
                    )
          );

          Console.WriteLine("Changed from: {0}", 
                    entry.OriginalValues[prop]);

          Console.WriteLine("Changed to: {0}", 
                    entry.CurrentValues[prop]);
     }

     Console.WriteLine("Entity State: {0}", entry.State);

     Console.WriteLine("\n--> All Original Values");
     for (int i = 0; i < entry.OriginalValues.FieldCount; i++)
     {
          Console.WriteLine("{0}: {1}", 
                    entry.OriginalValues.GetName(i), 
                    entry.OriginalValues[i]);
     }

     _entities.SaveChanges();

     Console.ReadLine();
}

After modifying a property an object, we can use the ObjectStateManager to access state information such as, which properties were modified, those properties original values, their current values, and other helpful information.

To access this information we call the ObjectContext’s GetObjectStateEntry method passing in the Director’s EntityKey. This method returns the ObjectStateEntry for the specified Director object. To determine which properties have been modified, we call the ObjectStateEntries GetModifiedProperties method which returns a collection of the names of any properties whose current values are different from their original values.

To determine the original value of a property, we retrieve the value at a given index in the ObjectStateEntry’s OriginalValues collection. Since OriginalValues is an indexed collection we can specify either the number of the database column or the name of the column (or property) as such, entry.OriginalValues["name"]. We then use the CurrentValues collection to retrieve the current value of the modified property.

Lastly, for the purpose of illustration, we loop over the OriginalValues collection and output all of the Director object’s property names and their respective values.

Here is the output:

Modified Property: Name
IsDbNull: False
Changed from: Spike Jonze
Changed to: Adam Spiegel a.k.a "Spike Jonze"
Entity State: Modified

--> All Original Values
ID: 33
Name: Spike Jonze
Hometown: Rockville Maryland
Birthday: 10/22/1969
Advertisements

Using the Entity Framework: Delete Operation (Quick Reference)

How to Use the Entity Framework to Delete Records in a Relational Database

This quick reference is for those who are trying out the Entity Framework and want examples of how to perform everyday CRUD tasks. We’ll take a look at how to delete objects and associated objects using the Entity Framework.

Quick Reference Setup

Entity Framework & Linq to Entities: “Movies” Example Setup contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.

Delete a Movie object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Movie movieToDelete = 
          (from m in _entities.MovieSet
           where m.Title == "The Princess Bride"
	   select m).First();

     _entities.DeleteObject(movieToDelete);
     Console.WriteLine("--> {0}: Marked as Deleted in Model",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Deleted

     _entities.SaveChanges();
     Console.WriteLine("\n--> {0}: 
          Deleted from Model and Datasource",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Detached
     Console.ReadLine();
}

First we retrieve the Movie we wish to delete. To do so we make use of the First extension method on the Linq query. The First method returns a single object rather than a collection. We then call the ObjectContext’s DeleteObject method passing it the Movie object we retrieved. At this point the ObjectStateManager has marked the object as having a “Deleted” state, though the Movie object has not been deleted from the model or the database. Calling the ObjectContext’s SaveChanges method detaches the Movie from the model and deletes the corresponding record from the database.

Here is the output:

--> The Princess Bride: Marked as Deleted in Model
Entity State: Deleted

--> The Princess Bride: Deleted from Model and Datasource
Entity State: Detached

Delete a Director object and its associated Movie objects using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d => d.Name == "Spike Jonze").First();

     // Remember to Load associated objects
     spikeJonze.Movies.Load(); 

     Console.WriteLine("Number of Movies to Delete: {0}", 
               spikesMovies.Count());

     // Using ToList is also important
     foreach (var movie in spikeJonze.Movies.ToList())
     {
          _entities.DeleteObject(movie);
          Console.WriteLine("--> Movie {0}: 
                    Marked for Deletion", movie.Title);
     }

     _entities.DeleteObject(spikeJonze);
     Console.WriteLine("--> Director {0}: 
               Marked for Deletion", spikeJonze.Name);

     _entities.SaveChanges();
     Console.WriteLine("--> Director and 
               associated Movies Deleted");

     Console.ReadLine();
}

We retrieve the Director by passing a lambda expression to the Where extension method and use the First method to specify that we only want the first Movie object in the resulting collection. We then call the Load method on the Director’s Movies collection. This populates any Movies associated with the Director with values retrieved from the database. Each populated Movie object is added to the Movies collection. Neglecting to Load the Movies collection would result in an exception being thrown during the call to SaveChanges. This is because the Movies collection would appear to the ObjectContext to be empty, therefore, none of the Movies would be deleted. However, when SaveChanges is called, it would be determined that the Director does indeed have associated Movies in the database, and could therefore, not be deleted. Using the technique described in this example requires that objects must be loaded in order to be deleted.

Now that we have the Movies associated with the Director, we can loop over the collection and delete each Movie. Notice that the ToList extension method is called on the Director’s Movies collection. Doing so ensures that we are working with a separate instance of the Movies collection. If we tried to perform a delete operation on items in the actual collection we were iterating through, we would receive an error.

Once the Director’s Movies have been marked for deletion, we mark the Director for deletion as well. The subsequent call to the ObjectContext’s SaveChanges method results in the Director and his associated Movies being detached from the ObjectContext and deleted from the database.

Here is the output:

--> Number of Movies to Delete: 4

--> Movie Adaptation: Marked for Deletion
--> Movie Where the Wild Things Are: Marked for Deletion
--> Movie Human Nature: Marked for Deletion
--> Movie Being John Malkovich: Marked for Deletion

--> Director Spike Jonze: Marked for Deletion

--> Director and Associated Movies Deleted

Delete a Movie object without loading it using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     int movieID = 105;
     int directorID = 2;
			
     Movie princessBride = new Movie();
     princessBride.ID = movieID;
     princessBride.DirectorReference.EntityKey = 
               new EntityKey("MovieEntities.DirectorSet", 
                         "ID", directorID);

     _entities.AttachTo("MovieEntities.MovieSet", 
               princessBride);
     _entities.DeleteObject(princessBride);
     _entities.SaveChanges();

     Console.ReadLine();
}

Assuming we know the ID of a Movie object, we can delete it without having to load it into the ObjectContext. We do so by creating a new Movie object, setting its ID property to the known value, and creating the EntityKeys for any EntityReferences the object may have. We then pass the Movie object to the ObjectContext’s AttachTo method, delete the object, and save the changes.

Unfortunately, I’ve not yet discovered a way to delete objects based on a property value, such as Movie.DirectorID, without loading the objects into the ObjectContext or performing a Linq query, both of which would require a call to the database. If you are aware of a method for doing so, please leave a comment and let us all know.

Exploring EntityStates when Deleting a Movie object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Movie movieToDelete = 
          (from m in _entities.MovieSet
           where m.Title == "The Princess Bride"
	   select m).First();

     // Movie retrieved
     Console.WriteLine("--> {0}: Movie Retrieved", 
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}", 
          movieToDelete.EntityState); // Deleted

     EntityKey movieToDeleteKey = _entities.
          CreateEntityKey("MovieEntities.MovieSet", 
                                   movieToDelete);
     Console.WriteLine("Movie's EntityKey Value: {0}", 
          movieToDeleteKey.EntityKeyValues[0].Value);
     Console.WriteLine("DirectorReference 
          EntityKey is null: {0}", 
          movieToDelete.DirectorReference.EntityKey == null);
     Object deletedMovie = null;
     bool movieToDeleteExists = _entities.
          TryGetObjectByKey(movieToDeleteKey, 
               out deletedMovie);
     Console.WriteLine("Movie to Delete Exists
          in ObjectContext: {0}", 
          movieToDeleteExists);

     // Movie marked for deletion
     _entities.DeleteObject(movieToDelete);
     Console.WriteLine("\n\n--> {0}: Marked as Deleted in Model",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Deleted

     movieToDeleteKey = _entities.
          CreateEntityKey("MovieEntities.MovieSet", 
               movieToDelete);
     Console.WriteLine("Movie's EntityKey Value: {0}", 
          movieToDeleteKey.EntityKeyValues[0].Value);
     Console.WriteLine("DirectorReference 
          EntityKey is null: {0}", 
          movieToDelete.DirectorReference.EntityKey == null);
     deletedMovie = null; 
     movieToDeleteExists = _entities.
          TryGetObjectByKey(movieToDeleteKey, 
               out deletedMovie);
     Console.WriteLine("Movie to Delete Exists
          in ObjectConext: {0}", 
          movieToDeleteExists);


     // Movie detached from model and deleted from database
     _entities.SaveChanges();
     Console.WriteLine("\n\n--> {0}: 
          Deleted from Model and Datasource",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Detached

     movieToDeleteKey = _entities.
          CreateEntityKey("MovieEntities.MovieSet", 
               movieToDelete);
     Console.WriteLine("Movie's EntityKey Value: {0}", 
          movieToDeleteKey.EntityKeyValues[0].Value);
     Console.WriteLine("DirectorReference 
          EntityKey is null: {0}", 
          movieToDelete.DirectorReference.EntityKey == null);
     deletedMovie = null; 
     movieToDeleteExists = _entities.
          TryGetObjectByKey(movieToDeleteKey, 
               out deletedMovie);
     Console.WriteLine("Movie to Delete Exists
          in ObjectContext: {0}", 
          movieToDeleteExists);

     Console.ReadLine();
}

After marking the Movie for deletion, we are still able to make use of the object. In this case we grab the Movies EntityKey and make a call to the ObjectContext’s TryGetObjectByKey method. This method returns true if a Movie with the specified EntityKey exists in the model. It also creates a reference to the Movie and places it in the out parameter deletedMovie.

Calling the ObjectContext’s SaveChanges method detaches the Movie object from the model. The object retains its data values including its EntityKey, however, any relationships it might have had (such as the relationship used for the DirectorReference in this case) are lost. We are still able to retrieve the EntityKey from the detached object, however, the subsequent call to TryGetObjectByKey returns false because the Movie is no longer part of the ObjectContext.

Here is the output:

--> The Princess Bride: Movie Retrieved
Entity State: Unchanged
Movie's EntityKey Value: 97
DirectorReference EntityKey is null: False
Movie to Delete Exists in ObjectContext: True

--> The Princess Bride: Marked as Deleted in Model
Entity State: Deleted
Movie's EntityKey Value: 97
DirectorReference EntityKey is null: True
Movie to Delete Exists in ObjectContext: True

--> The Princess Bride: Deleted from Model and Datasource
Entity State: Detached
Movie's EntityKey Value: 97
DirectorReference EntityKey is null: True
Movie to Delete Exists in ObjectContext: False

Using the Entity Framework: Create Operation (Quick Reference)

How to Use the Entity Framework to Create Records in a Relational Database

This quick reference is for those who are trying out the Entity Framework and want examples of how to perform everyday CRUD tasks. We’ll take a look at how to create objects and manage relationships working with the Entity Framework’s occasionally unclear object model.

Quick Reference Setup

Entity Framework & Linq to Entities: “Movies” Example Setup contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.

Create a Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = Director.CreateDirector(
          0, 
          "Spike Jonze", 
          "Rockville Maryland", 
          "10/22/1969"
     );
     
     // Use the AddToDirectorSet method
     _entities.AddToDirectorSet(spikeJonze);

     // Could have also used the AddObject method
     // _entities.AddObject("MovieEntities.DirectorSet", 
     //     spikeJonze);

     Console.WriteLine("--> Director added to DirectorSet");
     Console.WriteLine("EntityKey is temporary: {0}", 
          spikeJonze.EntityKey.IsTemporary);

     _entities.SaveChanges();

     Console.WriteLine("--> Changes Saved");
     Console.WriteLine("EntityKey is temporary: {0}", 
          spikeJonze.EntityKey.IsTemporary);
     Console.WriteLine("EntityKey Key: {0}, 
          EntityKey Value: {1}", 
          spikeJonze.EntityKey.EntityKeyValues[0].Key,
          spikeJonze.EntityKey.EntityKeyValues[0].Value);

     Console.ReadLine();
}

We use the CreateDirector to initialize a new Director object. Notice that 0 is specified for the ID parameter. Though this argument is required, the value you provide is of no consequence. Once the Director is added to the DirectorSet, a temporary EntityKey is created. The call to SaveChanges adds the Director object’s data values to the database and the primary key resulting from the database insert is retrieved. From that point on the EntityKey’s value will be synchronized with the identity column for the Director record in the database.

There are multiple ways to add an entity object to the ObjectContext. Two of which are illustrated in this example. Which method you choose is a matter of preference.

Here is the output:

--> Director added to DirectorSet
EntityKey is temporary: True
--> Changes Saved
EntityKey is temporary: False
EntityKey Key: ID, EntityKey Value: 27

Create a Director object and an associated Movie object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = new Director { 
          Name = "Adam Spiegel a.k.a., Spike Jonze", 
          Hometown = "Rockville Maryland", 
          Birthday = "10/22/1969" 
     };
     _entities.AddToDirectorSet(spikeJonze);

     Movie wildThings = new Movie { 
          Title = "Where the Wild Things Are", 
          DateReleased = DateTime.Parse("10/1/2009") 
     };
     spikeJonze.Movies.Add(wildThings);

     _entities.SaveChanges();
     Console.ReadLine();
}

We use object initialization syntax to create a Director object and then add it to the ObjectContext’s DirectorSet collection. We then create a Movie object and add it to the Director’s Movies collection. Doing so creates a relationship (with corresponding temporary EntityKeys) between the Director and the Movie. Calling the SaveChanges method updates the database to reflect the changes we’ve made to the entity data model.

There are multiple ways to initialize object in CSharp. When working with the Entity Framework, I prefer to use object initialization syntax (used in this example) in lieu of using the CreateDirector factory method. Though there is a benefit to using the factory method in that you are forced to provide initial values for all properties. What you use is a matter of preference.

Create a Movie object and associate it with an existing Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director robReiner = _entities.DirectorSet.Where(
               d => d.Name == "Rob Reiner").First();

     Movie thePrincessBride = new Movie {
          Title = "The Princess Bride",
          DateReleased = DateTime.Parse("1/1/1987")
     };

     robReiner.Movies.Add(thePrincessBride);
     _entities.SaveChanges();
     Console.ReadLine();
}

First we load the appropriate Director object. Next we create the Movie object and add it to the Director’s Movies collection. Doing so creates the necessary relationship. Finally, we call the ObjectContext’s SaveChanges() method which inspects the context’s ObjectStateManager and commits any changes that had been made to the model’s entities or associations since it was created or since SaveChanges() was last called.

Create a Movie object and associate it with an existing Director object without loading the Director object using the Entity Framework

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     int robReinerID = 2;
     Movie thePrincessBride = new Movie {
          Title = "The Princess Bride (New)",
          DateReleased = DateTime.Parse("1/1/1987")
     };

     thePrincessBride.DirectorReference.EntityKey = new
          EntityKey("MovieEntities.DirectorSet",
                    "ID", robReinerID);
     _entities.AddToMovieSet(thePrincessBride);
     _entities.SaveChanges();
     Console.ReadLine();
}

Since we know the Director’s ID, there is no need to load the Director object in order to create the Movie. It is necessary, however, to set the EntityKey property of the DirectorReference (an EntityReference type). Note that the first argument passed to the EntityKey’s constructor is an EntitySet within the ObjectContext; e.g., MovieEntities.DirectorSet.

Exploring the Entity Framework’s ObjectStateManager

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director robReiner = _entities.DirectorSet.Where(
               d => d.Name == "Rob Reiner").First();

     Movie thePrincessBride = new Movie { 
          Title = "The Princess Bride", 
          DateReleased = DateTime.Parse("1/1/1987") 
     };

     robReiner.Movies.Add(thePrincessBride);
     IEnumerable<ObjectStateEntry> entries = 
          _entities.ObjectStateManager.
          GetObjectStateEntries(EntityState.Added);
				
     foreach (ObjectStateEntry entry in entries)
     {
          Console.WriteLine("Entity Set: {0}", entry.EntitySet);
	  Console.WriteLine("IsRelationship: {0}", 
               entry.IsRelationship);
	  Console.WriteLine("State: {0}", entry.State);
				
	  if (!entry.IsRelationship)
	  {
	     Console.WriteLine("EntityKey is null: {0}", 
                  entry.EntityKey.EntityKeyValues == null);
             Console.WriteLine("EntityKey is temporary: {0}", 
                  entry.EntityKey.IsTemporary);
	  }

          entry.AcceptChanges();
          Console.WriteLine("--> Changes Accepted");

	  if (!entry.IsRelationship)
	  {
	        Console.WriteLine("EntityKey is: {0}", 
                     entry.EntityKey.EntityKeyValues.First());
		Console.WriteLine("EntityKey is temporary: {0}", 
                     entry.EntityKey.IsTemporary);
	  }

          Console.WriteLine("State: {0}\n\n", entry.State);
     }

     // The following call to SaveChanges() does nothing
     // because calling AcceptChanges() on each entry updated
     // their respective states from "Added" to "Unchanged".
     _entities.SaveChanges(); 

     Console.ReadLine();
}

First we add a Movie to a Director’s collection of Movies. Doing so adds two ObjectStateEntries to the ObjectStateManager. ObjectStateEntries are used to track changes made to the entity model. One of the entries is for the Movie entity that was added and the second is for the relationship that was created between the Movie and the Director. We then grab the ObjectStateEntries where the EntityState equals “Added”. Looping over the ObjectStateEntries allows us to see various properties of the entries before and after AcceptChanges is called. When AcceptChanges is called on a given entry, its state is set to “Unchanged”. Therefore, the subsequent call to SaveChanges does nothing since the state of all ObjectStateEntries is “Unchanged” at the time SaveChanges is called. Retrieving a list of Movies would reveal that the Movie was not inserted into the database.

Here is the output:

Entity Set: FK_Movies_Directors
IsRelationship: True
State: Added
--> Changes Accepted
State: Unchanged


Entity Set: MovieSet
IsRelationship: False
State: Added
EntityKey is null: True
EntityKey is temporary: True
--> Changes Accepted
EntityKey is: [ID, 0]
EntityKey is temporary: False
State: Unchanged

Entity Framework & Linq to Entities: “Movies” Example Setup

The Entity Data Model Used in the “Movies” Example

Below are diagrams representing the database, entity data, and entity object model used in the Linq to Entities Quick Reference posts. The Quick References are meant to provide numerous examples of performing common CRUD (Create, Read, Modify, and Delete) tasks with Linq to Entities.

Visit: C# Entity Framework & Linq to Entities (Quick Reference)

Database Structure for the "Movies" Example

Database Structure for the "Movies" Example

Directors Database Records

Directors Database Records

Movies Database Records

Movies Database Records

Entity Diagram for the "Movies" Example

Entity Diagram for the "Movies" Example

This Entity Model was created by adding an ADO.NET Entity Data Model item to the solution and specifying that the model should be generated based on the Movies database. The model was then modified slightly using the Entity Designer within Visual Studio 2008. For instance, the FirstLastName property was changed to Name.
Class diagram of the entity data model for the "Movies" example.

Class diagram of the entity data model for the "Movies" example.

This class diagram is a visual representation of the Entity Framework object model for the Movies example and serves as a valuable resource for understanding its structure, properties, and methods. You can create such a class diagram in your Visual Studio 2008 project by adding a new Class Diagram item to the project, and then dragging the file representing your entity model (.edmx extension) from the Solution Explorer onto the Class Diagram’s design surface. Once the diagram has been created, right click on each of the classes and choose the “Show Base Class” option from the context menu. Doing so will include the core entity framework base classes, such as the ObjectContext class, to the diagram giving you a complete view into what’s available to you.

Using Linq to Entities: Read Operation (Quick Reference)

How to Use Linq to Entities to Retrieve Records from a Relational Database

This quick reference is for those who are trying out Linq to Entities and want plenty of examples of how to perform everyday data retrieval tasks such as joining records (entities) and filtering and sorting query results.

Quick Reference Setup

Entity Framework & Linq to Entities: “Movies” Example Setup contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.

Retrieve a list of Movie objects using a Linq to Entities query

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     var moviesList = (from m in _entities.MovieSet select m);

     foreach (var movie in moviesList)
     {
          Console.WriteLine(movie.Title);
     }
     Console.ReadLine();
}

A Linq query is used to retrieve all of the Movies from the database. The var keyword is used for the initialization of the moviesList variable to allow the compiler to dynamically determine its type. Notice that the var keyword is also used within the foreach construct. The var keyword was added to the C# language to support anonymous types in Linq and is meant to be used in these cases.

Access the ObjectQuery collection directly

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     foreach (Movie movie in _entities.MovieSet)
     {
          Console.WriteLine(movie.Title);
     }
     Console.ReadLine();
}

Loop over the MovieSet (ObjectQuery<TEntity>) collection directly without assigning it to another variable.

Retrieve a list of Movie objects using the ToList() extension method

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     List<Movie> moviesList = _entities.MovieSet.ToList();

     foreach (Movie movie in moviesList)
     {
          Console.WriteLine(movie.Title);
     }
     Console.ReadLine();
}

The ToList() extension method is used to retrieve all of the Movies from the database. When the type can be inferred by the compiler, it isn’t necessary to specify the type, (e.g. ToList<Movie>()) in the method’s signature. Since MovieSet implements IEnumerable<T> the compiler knows the type, therefore, calling ToList() will do the trick.

Retrieve a sorted list of Movie objects using a Linq to Entities query

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     var moviesList = (from m in _entities.MovieSet
                       orderby m.Title ascending,
                               m.DateReleased descending
                       select m);

     foreach (Movie movie in moviesList)
     {
          Console.WriteLine("{0} {1:d}", movie.Title,
                                         movie.DateReleased);
     }
     Console.ReadLine();
}

The orderby Linq operator is used to specify which properties should be used to sort the collection.

Retrieve a filtered list of Movie objects using a Linq to Entities query

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     var moviesList = (from m in _entities.MovieSet
                       where m.Title == "Rumble Fish"
                       select m);

     foreach (Movie movie in moviesList)
     {
          Console.WriteLine(movie.Title);
     }
     Console.ReadLine();
}

An expression is used to specify the value of the Title property for the Movies we wish to retrieve. Note that this query returns a collection of Movies and not a single Movie.

Retrieve a single Movie object using a Linq to Entities query and the First() extension method

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Movie movGodfather = (from m in _entities.MovieSet
                           where m.Title == "The Godfather"
                           select m).First();

     Console.WriteLine(movGodfather.Title);
     Console.ReadLine();
}

An expression is used to specify the value of the Title property for the Movies we wish to retrieve. We make use of the First() extension method in order to retrieve a single Movie object. If there are multiple matches, this method retrieves the first in the list.

Retrieve a single anonymous object using a Linq to Entities navigation property to join related records

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     var movGodfather = (from d in _entities.DirectorSet
                         from m in d.Movies
                         where m.Title == "The Godfather"
                         select new { m.Title, d.Name }).First();

     Console.WriteLine("{0} by {1}", movGodfather.Title,
                                     movGodfather.Name);
     Console.ReadLine();
}

Two from operations are included in the query to retrieve information from associated objects. The resulting type is an anonymous object with Title and Name properties. Notice the use of the var keyword to specify that the query returns an anonymous type.  The select Linq operator statement uses object initialization syntax to specify the properties to retrieve from each object. The property names for the anonymous type could also be defined explicitly. By way of example: new { Title = m.Title, DirectorName = d.Name }.

Retrieve a collection of anonymous objects using a Linq to Entities navigation property to join related records

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     var moviesList = (from d in _entities.DirectorSet
                       from m in d.Movies
                       where m.Title == "The Godfather"
                       // Or grab only Movies with Titles
                       // that start with "The".
                       // where m.Title.StartsWith("The")
                       select new { m.Title, d.Name });

     foreach (var movie in moviesList)
     {
          Console.WriteLine("{0} by {1}", movie.Title,
                                          movie.Name);
     }
     Console.ReadLine();
}

The Director.Movies navigation property is an EntityCollection<TEntity> that provides interoperability with Linq queries. When doing a join in this fashion the order of the from statements matters. It is necessary to specify the “one” side of a “one to many” relationship prior to specifying the “many” side of the relationship. So first we specify Directors in the DirectorSet collection and then we specify the Movies associated with each Director by way of Director.Movies.

Retrieve a collection of objects using a subquery in Linq to Entities

private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     var moviesList = (from d in _entities.DirectorSet
                       from m in d.Movies
                       where m.Title == 
                             (from mov in d.Movies
                              where mov.Title == "The Godfather"
                              select mov.Title).FirstOrDefault()
                       select new { m.Title, d.Name });

     foreach (var movie in moviesList)
     {
          Console.WriteLine("{0} by {1}", movie.Title,
                                          movie.Name);
     }
     Console.ReadLine();
}

The FirstOrDefault() extension method is used within the subquery since First() can only be used at the very end of a Linq query statement as the final query operation. Of course, the above query is only meant to serve as an example. There would be no reason to perform a subquery since where m.Title == "The Godfather" would do the trick.

C# Entity Framework & Linq to Entities (Quick Reference)

The Entity Framework & Linq to Entities: CRUD (Create, Read, Update, Delete) Tasks with CSharp

The Entity Framework in conjunction with Linq to Entities seems to be Microsoft’s ORM (Object Relational Mapping) flavor of the moment. The technology is not without its downsides, but given that the company is making moves to deprecate Linq to SQL by merging that product’s feature set into that of Linq to Entities’; it appears to be the horse Microsoft is betting on. If you’re interested in getting behind Microsoft on this one (as if you had a choice), then there are probably some pretty fundamental tasks you’ll want to be able to perform from the outset.

In this series of posts, I’ll break down how to use Linq to Entities to perform common CRUD (Create, Read, Update, and Delete) tasks with an entity data model generated by Visual Studio 2008 and based on the Entity Framework. I wish I could say that the entity data model model is so obvious that a quick glance at a class diagram would be all one would need to figure these things out. If that were the case, however, I would not have felt the need to write this post, and you would not have found your way to it through the Googles.

Quick References

Quick Reference Setup

Entity Framework & Linq to Entities: “Movies” Example Setup contains diagrams representing the database structure, entity data model, and entity object model used in the Linq to Entities Quick References.

C# Modifiers (Quick Reference)

Overview of CSharp .NET Access Modifiers

Access Modifiers are used to define the “visibility” of a type (class) or the members of a type. The full list of access modifiers is public, private, protected, internal, and protected internal.

Definitions

Access Modifier Description
public Access is not restricted.
private Access is limited to the containing type.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protected internal Access is limited to the current assembly or types derived from the containing class.

Notes

If no access modifier is specified for a given class or member definition, the appropriate default access modifier is applied by the compiler. Also, types, nested types, and type members each have a unique subset of access modifiers that can be specified.

Access Modifiers for Types

  • Non-nested Types
    • Implicit default
      • internal
    • Allowable access modifiers
      • public
      • internal
  • Nested Types
    • Implicit default
      • private
    • Allowable access modifiers
      • private
      • protected
      • protected internal

Access Modifiers for Type Members

  • Implicit default
    • private
  • Allowable modifiers
    • public
    • private
    • protected
    • internal
    • protected internal

Code Examples

Default Access Modifiers

class Person //   Implicitly internal
{
     Person()   {}  //   Implicitly private
}
  1. Since no access modifier is specified for the Person type, its accessibility level defaults to internal.
  2. Since no access modifier is specified for the Person() constructor method (a member of the Person type), its accessibility level defaults to private.

Explicitly Defined Access Modifiers

internal class Person // Explicitly internal
{
	private Person() {}  // Explicitly private
}

Here, the default access modifiers for the type and the type’s member are defined explicitly.

Explicitly Defined Access Modifiers

public class Person // Explicitly public
{
	public Person() {}  // Explicitly public
}
  1. The class is made public and is accessible to code from external assemblies.
  2. The constructor method is made public and is accessible from code defined outside of the Person class.

Other Modifiers

Definitions

Modifier Description
abstract Indicates that a class is intended only to be a base class of other classes. Abstract classes cannot be instantiated directly, though classes that derive from an abstract class can be instantiated.
const Specify that the value of the field or the local variable cannot be modified.
override Provide a new implementation of a virtual member inherited from a base class.
readonly Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class.
sealed Specify that a class cannot be inherited.
static Declare a member that belongs to the type itself rather than to a specific object.
virtual Declare a method or an accessor property whose implementation can be changed by an overriding member in a derived class.