C# language features for working with data

In this document, you will learn about the C# language features for working with data. In addition, you will begin using the MyNorthwind.edmx data model that you created earlier.

.

This post was most recently updated in October 2011.

.

A brief introduction to the enabling C# language features

In this section, we will cover the following:

  • Object context
  • Object set
  • C# generics
  • LINQ – language integrated query
  • Lambda expressions

.

Object context 

An object context is an instance of the ObjectContext class. (Often, it is referred to simply as “context“.)

Note: In Entity Framework 4.1, we can also use the simpler DbContext.

.

In code, you create an object context as a new instance of your Entity Framework data model’s “entity container”. (The entity container is a container/wrapper for a set of entities.) For example, we recently have been working with a copy of the Northwind database, and we created an Entity Framework data model for it. Its entity container name was “MyNorthwindEntities”. Therefore, the code would be:

var context = new MyNorthwindEntities();

By convention, we typically use “context” as the instance name. In addition, as a programming best practice, we wrap the creation in a using {} statement block, so that the resource is released as soon as possible.

The object context provides access to the entity types in your Entity Framework data model. The object context is a “work area” for the operations you perform on the entity types. For example:

  • The object context holds the results of a fetch
  • It is the target for add, change, and remove operations

.

When you perform an add, change, or remove operation on the object context, you must save it, which will persist the change in the data store.

An object context encapsulates a connection to the data store, metadata about the model, and a set of methods to support its functionality.

Study these references for more on the object context.

ObjectContext Class (MSDN)

DbContext Class (MSDN)

.

Object set

You have just learned that the object context provides access to the entity types in your model. Each entity type appears as a property of the object context. The type of the property is ObjectSet.

Note: In Entity Framework 4.1, it is a DbSet.

.

An object set is the target for read, add, change, and remove operations. For example, if you have an object context instance named “context”, and you wish to read the “Customers” entity as a generic list (of Customer objects), you would call this method:

context.Customers.ToList()

Skim this reference to view the wide range of operations that are supported on an object set:

ObjectSet<TEntity> Class (MSDN)

DbSet<Of TEntity> Class (MSDN)

.

Generics

As you have learned, C# generics enable you to define and use data structures (e.g. objects) in a type-safe manner, and perform operations on the data structures without the need to define an operation implementation for each allowable type. Generics also help the developer avoid cumbersome or inconvenient cast/convert syntax and operations, and code bloat (from having to define type-specific code blocks).

Generics were added to C# in 2005.

In this course, we use generics most often with collection classes. This need matches up very well with the fact that we are working with Entity Framework data model entity types. The advantage of generics is that we do not have to define type-specific methods or operations. We use the same generic type (e.g. List<T>) to refer to a collection of “Customers”, or to a collection of “Products”.

The compiler and runtime provide type safety, and therefore error-free coding and execution. However, do not think that you will lose access to type-specific members (like the specific property names in “Customer”, like “CustomerName”, “City”, and so on). Instead, with a generic, you are assured of being able to use/access the type-specific members, as first-class members.

For more, read/skim the following article, and the articles it links to:

Introduction to Generics (C# Programming Guide) (MSDN)

Another getting-started reference:

Generics in the .NET Framework (MSDN)

.

LINQ – language integrated query

LINQ is a C# language feature that supports in-language/in-band operations on data. The operations – known as query expressions – include the full range of read, add, change, and remove. The data store can include a wide range of possibilities, from in-memory object collections, to the file system, a relational database, and a remote/cloud store.

The LINQ feature was added to C# in 2007.

LINQ defines a set of language extensions, most notably the following:

  • A query syntax
  • Implicitly-typed variables
  • Anonymous types
  • Object initializers
  • Lambda expressions

.

The LINQ syntax defines a set of query operators. For those familiar with relational database querying, the LINQ query operators will appear familiar. A typical query expression (that follows the LINQ pattern) consists of these parts:

from …
where …
orderby …
select …

A typical query expression looks like this:

var query = from m in myCollection
            where m.LastName.StartsWith("M")
            orderby m.LastName
            select m;

.

In the “from” clause, “m” is a local range variable, which represents the items in the data source during the query.

For more examples, study the “Getting started…” section of the LINQ article by Hejlsberg and Box (linked below).

LINQ is not an interim technology, and it will not be replaced in a future version of the language. It is here to stay, so you cannot avoid learning LINQ and using it in your code. As noted earlier, it supports operations on data. Well, you do that in almost every one of your C# programs. So, learn it, and use it.

To get started learning about LINQ, study these resources:

.

LINQ: .NET Language Integrated Query, by Anders Hejlsberg and Don Box

Be sure to read at least these sections:

  • .NET Language-Integrated Query
  • Getting Started with Standard Query Operators

.

Wikipedia LINQ article , particularly the Language extensions section

Be sure to pay special attention to this section:

Language extensions

.

Lambda expressions

Many LINQ query operators enable the user to provide/supply a function, as an argument. The function could extract, filter, or project – the developer decides its behaviour.

The function syntax is known as a lambda expression in C#. (It is often referred to as an inline method. More generically, it is known as an anonymous function.) The syntax below shows a lambda expression that returns an entity object that matches a specific condition:

c => c.CustomerID == 23

The return type is inferred from the context in which it is used. In other words, if the lambda expression is used as an argument to a LINQ query operator that is supposed to return an entity object, then the return type of the lambda expression above is the entity object type.

Anonymous functions can “see” the local variables in the surrounding methods. Repeating the example syntax above, assume that the method that surrounds the lambda expression includes a local variable named “custID”, and the variable held the value “23”. The new syntax would be:

c => c.CustomerID == custID

How do you read or pronounce this syntax? As suggested by Hejlsberg and others (see this StackOverflow article), it can be read as any one of the following:

c becomes (the result of) c.CustomerID equals custID

c for which c.CustomerID is equal to custID

c such that c.CustomerID is equal to custID

c maps to c.CustomerID equals custID

c lambda of c dot CustomerID is equal to custID

.

This will get you started with lambda expressions. For more, study the “Lambda Expressions and Expression Trees” section of the LINQ article by Hejlsberg and Box.

.

Working with our data model

Whenever we want to work with our data model, we use an object context, which was described earlier. As a reminder, an object context provides access to the entity types in your Entity Framework data model. The object context is a “work area” for the operations you perform on the entity types.

The right way to use a context is to initialize it in a using statement, which ensures that the context is disposed of properly at the end of the code block.

Once the context has been initialized, the typical usage pattern looks like this:

context.EntitySet.Action()

  • context” is the instance of the object context
  • EntitySet” is the name of the entity set that we want to work with
  • Action()” is the method we want to call; note that these methods can be chained/stacked (e.g. Action1().Action2().Action3())

.

Typical actions/methods that we will regularly use include Find(), First(), FirstOrDefault(), ToList(), Where(), OrderBy(), and Count(), as well as AddObject(), and DeleteObject(), and SaveChanges().

.

Introductory code examples

To see the data model in action, run and study the following code examples:

MyNorthwind.edmx Simple Tasks

.


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: