The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Finding Entities see http://msdn.com/data/jj573936


 

Introduction

Version 4.1 of the Entity Framework contains both the Code First approach and the new DbContext API. This API provides a more productive surface for working with the Entity Framework and can be used with the Code First, Database First, and Model First approaches. This is the third post of a twelve part series containing collections of patterns and code fragments showing how features of the new API can be used.

The posts in this series do not contain complete walkthroughs. If you haven’t used EF 4.1 before then you should read Part 1 of this series and also Code First Walkthrough or Model and Database First with DbContext before tackling this post.

Finding entities using a query

DbSet and IDbSet implement IQueryable and so can be used as the starting point for writing a LINQ query against the database. This post is not the appropriate place for an in-depth discussion of LINQ, but here are a couple of simple examples:

using (var context = new UnicornsContext())
{
    // Query for all unicorns with names starting with B
    var unicorns = from u in context.Unicorns
where u.Name.StartsWith("B")
select u;
// Query for the unicorn named Binky var binky = context.Unicorns
.Where(u => u.Name == "Binky")
.FirstOrDefault(); }

Note that DbSet and IDbSet always create queries against the database and will always involve a round trip to the database even if the entities returned already exist in the context.

Finding entities using primary keys

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.

Find is different from using a query in two significant ways:

  • A round-trip to the database will only be made if the entity with the given key is not found in the context.
  • Find will return entities that are in the Added state. That is, Find will return entities that have been added to the context but have not yet been saved to the database.

Finding an entity by primary key

The following code shows some uses of Find:

using (var context = new UnicornsContext())
{
    // Will hit the database
    var unicorn = context.Unicorns.Find(3);

    // Will return the same instance without hitting the database
    var unicornAgain = context.Unicorns.Find(3);

    context.Unicorns.Add(new Unicorn { Id = -1 });

    // Will find the new unicorn even though it does not exist in the database
    var newUnicorn = context.Unicorns.Find(-1);

    // Will find a castle which has a string primary key
    var castle = context.Castles.Find("The EF Castle");
}

Finding an entity by composite primary key

In the model presented in Part 1 of this series, the LadyInWaiting entity type has a composite primary key formed from the PrincessId and the CastleName properties—a princess can have one lady-in-waiting in each castle. The following code attempts to find a LadyInWaiting with PrincessId = 3 and CastleName = “The EF Castle”:

using (var context = new UnicornsContext())
{
    var lady = context.LadiesInWaiting.Find(3, "The EF Castle");
}

Note that in the model the ColumnAttribute was used to specify an ordering for the two properties of the composite key. The call to Find must use this order when specifying the two values that form the key.

Summary

In this part of the series we showed how to find entities using LINQ queries and also how to use Find to find entities using their primary key values.

As always we would love to hear any feedback you have by commenting on this blog post.

For support please use the Entity Framework Forum.

Arthur Vickers
Developer
ADO.NET Entity Framework