-
Notifications
You must be signed in to change notification settings - Fork 1
BASE.data.DataContext
The DataContext helps developers with handling changes to models. Think of the DataContext as a transaction handler. If you have the need to query for data and modify some of the data and the relationships among that model, then the DataContext is your answer. It handles relationships for you, so you don't have to think about updating foreign keys, or primary keys from a service. The DataContext wants you to think about data as it should be, just data, not so much about the storage structure for persisting the data.
The DataContext uses many of the other technologies to handle complexity. It uses Queryables for querying your Service, Futures for asynchrony while interacting with the Service, and Observables for knowing whether or not properties have changed on a instance of a model.
Here is a list of the other technologies that you need to understand when using the DataContext.
The DataContext is perfect to use behind a form. Forms usually consist of related data on one or more models. The changes that happen on the form should be handled with the DataContext on a save button click. Here is how it might look.
//... var edm = new Edm(); var service = new Service(edm); //... saveButton.addEventListener("click", function(){ var firstName = firstNameInput.value; var lastName = lastNameInput.value; var id = idInput.value; var dataContext = new BASE.data.DataContext(service); dataContext.people.firstOrDefault(function(expBuilder){ return expBuilder.property("id").isEqualTo(id); }).then(function(person){ person.firstName = firstName; person.lastName = lastName; dataContext.saveChangesAsync().then(function(response){ console.log("Saved Data!"); }); }); }); //...
You'll notice that the life of the DataContext is with in the click function. A Service on the other hand is a long lived object that keeps no memory of the objects that are being queried for. It's simple the portal to the persistent data layer. The DataContext uses the service to maintain the data in a transaction.
When using a DataContext we need a service, and a service needs an edm (Entity Data Model) . The edm describes the model as it appears in storage, and how the data is associated.
DataSets are added automatically from the definitions of the model in the edm. The edm relies on the collectionName property found on the model description.
//... var edm = new BASE.data.Edm(); var personModel = { type: Person, collectionName: "people", properties: { id: { type: Integer, primaryKey: true, autoIncrement: true }, firstName: { type: String }, lastName: { type: String } } }; edm.addModel(personModel); var service = new BASE.data.services.InMemoryService(edm); //... var dataContext = new BASE.data.DataContext(service); console.log(dataContext.people); // ==> DataSet //...