DPS907 notes – Thu Sep 24

Associations, continued. The “command” pattern.


Associations among entity classes

In your ASP.NET MVC web apps course, you probably had a reasonable treatment of associations.

In the previous class session, we refreshed your memory about one to many associations.

Today, we’ll discuss some others, and study a code example (named AssociationsOther):

  • one to one
  • many to many
  • self-referencing one to one
  • self-referencing one to many

The problem domain that the code example covers is a workplace. There are three entities, Employee, JobDuty, and Address.

A workplace has employees. Employees have job duties, usually one or more. However a job duty is often performed by many employees. Also, an employee lives somewhere, and works somewhere – these are addresses.

The class diagram below is from this week’s code example, AssociationsOther. Click to open it in its own tab/window.



One to one

An Employee has one “home” Address, and one “work” Address.

From the Address perspective, it is linked to an Employee.

When writing the entity classes, you must know the following, and be aware of some rules:

  • In this association, you MUST select a “principal” end of the association, and a “dependent” end
  • We will decide that the Employee is the principal end
  • This means that an Employee object can OPTIONALLY have an associated Address object – an Employee object can be created, without having an already-existing Address object
  • However, as a result, the Address is the dependent end
  • This means that an Address object MUST have an associated Employee object – an Address object cannot exist without an associated Employee object, so when you create an Address object, you must know about the associated Employee object

How do you code this?

It’s simple. Two tasks:

In the dependent class (Address), add the [Required] data annotation attribute to the navigation property that points to the principal class. Here, in other words, add [Required] to the “Employee” property.

public Employee Employee { get; set; }

Add another property, a nullable int. Its name is a composite name – EmployeeId.

public int? EmployeeId { get; set; }

How do you use this?

  1. Make sure that you have a reference to a principal object (e.g. an Employee)
  2. When creating a dependent object (e.g. an Address), set its “Employee” property to the principal object
  3. Set the EmployeeId property to the principal object’s identifier


Many to many 

An Employee can have several ‘job duties’ (e.g. teacher, researcher, coordinator), and a ‘job duty’ is performed by many Employees (e.g. School of ICT coordinators include Peter McIntyre, Ian Tipson, Nagham Kubba, etc.).

Maybe surprisingly, this is also actually easy. Simply add collection properties to each class, similar to a ‘one to many’ association.


Self-referencing one to one, to the same entity

An Employee has a supervisor/manager, who is also an Employee.

When writing the entity class, you must know the following, and be aware of some rules:

  • Two properties are required
  • One property is a nullable int – it will hold the identifier of the associated object
  • The other property is the class data type

For example:

// Self-referencing one-to-one
// Two properties are required
public int? ReportsToEmployeeId { get; set; }
public Employee ReportsToEmployee { get; set; }


Self-referencing one to many, to the same entity

A supervisor/manager Employee has a collection of Employees supervised/managed.

This is actually easy, as you may speculate. Simply add a collection property; its data type is the class data type.


Are associations always required?

When you are writing entity classes, are associations required among all classes?


It is not necessary to ‘connect’ every class to another. This technique is often used for data that is used for lookup or validation purposes.


Learn more about this topic theme

In this web services programming course, and in the prerequisite web apps programming course, we use a learning strategy that enables the student to focus on the important and most-used associations among entities. The Entity Framework, and its technologies, offers much more than we have time to cover in this course.

Therefore, as you read/skim the linked resources below, use your critical thinking skills to put a topic into the proper context and usage pattern. In other words, don’t be literal in how you use and apply the information.

The biggest difference-maker for us is that we are writing web services and web apps. As a result, operations on data are atomic – a ‘read’ is done as a database server connection open, a read, and an immediate close. Similarly, a ‘write’ is done as an open, a write, and an immediate close. Many of the discussions in the linked documents (below) are for runtime environments where a database connection is persisted as a longer-lifetime object. So, if you have questions about syntax and differences with what you’ve learned so far, ask your professor.

Microsoft – Entity Framework Relationships & Navigation Properties

Microsoft – Entity Framework Code First Conventions, Relationship Convention section

Morteza Manavi – Associations in EF Code First – a multi-part series; parts 1, 2, and 3 are useful

MSDN Entity Framework topic page, lots of good stuff here to pick-and-choose from


Handling ‘commands’ in a web service

In the past few weeks, we have been learning to design and code a web service by thinking of it as an API to a database-like data store. You have learned how to handle the typical CRUD operations (create, retrieve, update, delete) normally associated with data management. The HTTP methods map nicely to these operations, and that familiarity has helped you make progress.

It’s time to expand our thinking, beyond data management. How? By adding the ability to handle commands and operations that may or may not be easily mapped to data management. (Yes, in most cases, the command will change the data/state of one or more resources.)

What kind of commands or operations could be done? Anything. For example, you could cause the web service to send a message (e.g. an email, or text message) to a list of pre-configured recipients, and then log the action. Or, it could increase the hourly wage 5% for all employees in a certain department. Or, set/save a photo for a resource. The point is that the web service is now doing a better job of servicing a use case.


How to think about this concept

A web service is NOT intended to be simply a thin layer on top of a data store. Instead, it is intended to be a gateway to the richness of an application / problem / business domain – all of its operations and workflows.

Today, you’ll get a gentle introduction to this concept. This will prepare you for more interesting scenarios in a few weeks. You can – and should – practice this concept in Lab 2.


Implementing this concept

There are two ways to look at any of the example tasks described above:

  1. As a command, where we state our intent – do this, or do that
  2. As a data management task, where we specifically, technically, and atomically set/update data properties to specific values

Which is the more natural concept to understand? Everyone can understand #1. Only programmers would care enough to understand #2.

How do we map commands to resources?

By convention, we typically send a PUT request to a resource. The underlying method has code that carries out our intent.

To illustrate this concept, study the AssociationsOther code example. It implements a command that enables a request to set (or configure) an employee with a supervisor:



A command needs the following code:

  • A resource model, that defines the necessary data
  • A controller method that listens for the request
  • A manager method that does the work

Study the following diagram, and then the AssociationsOther code example. Click the diagram to open it full size in its own tab/window.



Is this a standard?

No, but it’s a principle named “command-query separation“, or CQRS.

CQRS states that a command does something but does not return data to the caller. (In contrast, a query does not change the state of the data, but it does return data to the caller.)

Therefore, the controller method return type will be void, which automatically creates an HTTP 204 status code. In other words, when handling a ‘command’, we simply execute the command silently, without any data feedback to the requestor (other than the HTTP 204, which is one of the HTTP success status codes).

It is also possible that you could decide to return HTTP 202 (Accepted). Some developers and thought leaders advocate this alternative, for some situations. Please carefully read the RFC, and then decide whether it is suitable for your use case.


What else do I need to know?

Here’s a few other important things to know about HTTP.

In HTTP, the GET method is ‘safe’. A safe method does not change the state of a resource.

These methods are ‘unsafe’: POST, PUT, DELETE.

We must also consider idempotence. In brief, a method is ‘idempotent’ if repeated execution has the same effect.

In HTTP, GET, PUT, and DELETE are idempotent. (Why? Think about it.) POST is not idempotent.


Interesting readings

Exposing CQRS Through a RESTful API – Ali Kheyrollahi


















%d bloggers like this: