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
Advertisements

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.