Querying local data

Description and code samples
Table of Contents
Description

What it is

Local data represents in-memory data which includes:

  1. Entities loaded from the database; and
  2. New u entity objects added to the context, but not yet persisted

It will exclude entity objects that have been marked for deletion.

Local data is accessed through the DbSet.Local property. It returns an object of type ObservableCollection<TEntity>. This type allows to subscribe event handlers in order to be notified whenever:

  • New objects were added to the DbContext; or
  • Entity objects previously loaded into memory were marked for deletion.

When to use it

Local data should be used to:

  • Avoid sending multiple queries to the database when the required data is already in-memory;
  • Avoid passing around list of entity objects through several blocks of code;
  • Added new entity objects are relevant for the query results
Operations
Accessing to the Local data
How to do it
  using (var context = new BreakAwayContext())
  {
    var count = context.Destinations.Local.Count;
    Console.WriteLine("Destinations in memory: {0}", count);
  }
Querying the Local data through a LINQ query
How to do it
 using (var context = new BreakAwayContext())
  {
    context.Destinations.Load();

    var sortedDestinations = from d in context.Destinations.Local
                             orderby d.Name
                             select d;

    Console.WriteLine("All Destinations:");
    foreach (var destination in sortedDestinations)
    {
      Console.WriteLine(destination.Name);
    }

    var aussieDestinations = from d in context.Destinations.Local
                             where d.Country == "Australia"
                             select d;

    Console.WriteLine();
    Console.WriteLine("Australian Destinations:");
    foreach (var destination in aussieDestinations)
    {
      Console.WriteLine(destination.Name);
    }
  }
Subscribe event handlers for notification when Local data changes

Local raise an event of type CollectionChanged whenever the contents of Local changes. This occurs when:

  • New entity objects were added to the DbContext
  • An entity object previously loaded was marked for deletion
How to do it
using (var context = new BreakAwayContext())
  {
    context.Destinations.Local
      .CollectionChanged += (sender, args) =>
    {
      if (args.NewItems != null)
      {
        foreach (Destination item in args.NewItems)
        {
          Console.WriteLine("Added: " + item.Name);
        }
      }

      if (args.OldItems != null)
      {
        foreach (Destination item in args.OldItems)
        {
          Console.WriteLine("Removed: " + item.Name);
        }
      }
    };