Working with Entities
All persistent data is represented in LightSpeed as entities. An entity represents a business object with identity. It can be as big as a company or as small as a single order line. Of course, an entity can have associations to other entities, allowing an aggregate to represent a rich business domain. An entity can be loaded, modified and saved, and retains its identity throughout its lifecycle.
The Unit of Work
When you work with entities, you normally do so as part of a unit of work. The unit of work pattern is described as:
Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
In LightSpeed, a unit of work represents a business transaction in progress. It tracks the entities involved in that business transaction, takes care of loading entities from the database if required, and provides a way to save any changes made in the course of the business transaction. Roughly speaking, a unit of work is a collection of entities and their pending database operations.
A unit of work is represented in LightSpeed as the IUnitOfWork interface. IUnitOfWork provides operations to load, add and remove entities, and to save pending changes.
The basic process of working with entities in LightSpeed is therefore very simple:
· Begin a unit of work.
· Perform whatever combination of loads, adds, updates and removals are required for the business function you’re implementing.
· Save any pending changes in the unit of work.
· End the unit of work.
During this process, the unit of work object automatically:
· Tracks loaded entities in an identity map.
· Tracks entity state changes, so that it knows which entities if any need to be saved.
· Updates change tracking and versioning information if required.
· Connects to the database as and when required.
The LightSpeedContext Object
A LightSpeedContext object represents the configuration and connection settings for a particular database instance. A LightSpeedContext is like a souped-up connection string: in addition to the physical connectivity information of the connection string, the context also specifies the database engine, mapping conventions, logging behaviour and several other options.
Most applications require only one LightSpeedContext, representing the application database and the way the application maps to that database. Those settings won’t change over the course of the application, though they may of course be different for different instances of the application. You’ll therefore normally create your LightSpeedContext object as a static or singleton object – there’s no benefit, and some disadvantages, to creating a new LightSpeedContext every time you need one.