Finding entities using primary key

Description and code samples
Table of Contents
Description

How to do it

The DbContext API exposes a DbSet:Find() method which accepts a value to be searched for will return the corresponding entity object if it is found.

If there is no entity with the parameterized key, the method will return NULL.

How it works

The Find method applies the search both on persisted and non-persisted data acording the following rules:

  1. Seach in memory for an existing entity that has been loaded from the database or attached to the context;
  2. Search at added objects that have not yet persisted to the database;
  3. Seach in the database for entities that have not yet been loaded into memory.

 

Find

The DbSet.Find method can not be used if the target object is to be searched using another value other then the primary key or if the search must consider related data.

Operations
Find a single entity using the primary key
How to do it
using (var context = new BreakAwayContext())
  {
    var destination = context.Destinations.Find(id);
    if (destination == null)
    {
      Console.WriteLine("Destination not found!");
    }
    else
    {
      Console.WriteLine(destination.Name);
    }
  }
Find a single entity using the primary key (2)

Since the DbSet.Find return NULL in case of a single entity, it can be combined Find with the ?? operator that allows to provide an alternate value to return if some code returns NULL.

How to do it
using (var context = new BreakAwayContext())
{
    var ssn = 123456789;

    var person = context.People.Find(ssn)
      ?? context.People.Add(new Person
      {
        SocialSecurityNumber = ssn,
        FirstName = "<enter first name>",
        LastName = "<enter last name>"
      });

    Console.WriteLine(person.FirstName);
}
How to use it
using (var context = new BreakAwayContext())
{
    var ssn = 123456789;

    var person = context.People.Find(ssn)
      ?? context.People.Add(new Person
      {
        SocialSecurityNumber = ssn,
        FirstName = "<enter first name>",
        LastName = "<enter last name>"
      });

    Console.WriteLine(person.FirstName);
}
Find a single entity using a composite primary key

Entity Framework supports entities that have composite keys, that is, entities where the key is made up of two or more properties.

To locate entities with a composite key, the Find must passed to method in the same order they appear in the Model.

How to do it
using (var context = new BreakAwayContext())
  {
    var passport = context.Passports.Find("USA", "123456789");
    if (passport == null)
    {
      Console.WriteLine("Passport not found!");
    }
    else
    {
      Console.WriteLine(passport.Name);
    }
  }