Show:

EntityManager Class

Instances of the EntityManager contain and manage collections of entities, either retrieved from a backend datastore or created on the client.

Methods

<ctor> EntityManager

(
  • [config]
)

Parameters:

  • [config] Object | String optional

    Configuration settings or a service name.

    • [serviceName] String optional
    • [dataService] DataService optional

      An entire DataService (instead of just the serviceName above).

    • [metadataStore=MetadataStore.defaultInstance] MetadataStore optional
    • [queryOptions] QueryOptions optional
    • [saveOptions] SaveOptions optional
    • [validationOptions=ValidationOptions.defaultInstance] ValidationOptions optional
    • [keyGeneratorCtor] Function optional

Example:

At its most basic an EntityManager can be constructed with just a service name

var entityManager = new EntityManager( "breeze/NorthwindIBModel");

This is the same as calling it with the following configuration object

var entityManager = new EntityManager( {serviceName: "breeze/NorthwindIBModel" });

Usually however, configuration objects will contain more than just the 'serviceName';

var metadataStore = new MetadataStore();
var entityManager = new EntityManager( {
    serviceName: "breeze/NorthwindIBModel", 
    metadataStore: metadataStore 
});

or

return new QueryOptions({ 
    mergeStrategy: obj, 
    fetchStrategy: this.fetchStrategy 
});u
var queryOptions = new QueryOptions({ 
    mergeStrategy: MergeStrategy.OverwriteChanges, 
    fetchStrategy: FetchStrategy.FromServer 
});
var validationOptions = new ValidationOptions({ 
    validateOnAttach: true, 
    validateOnSave: true, 
    validateOnQuery: false
});
var entityManager = new EntityManager({ 
    serviceName: "breeze/NorthwindIBModel", 
    queryOptions: queryOptions, 
    validationOptions: validationOptions 
});

acceptChanges

()

Calls EntityAspect.acceptChanges on every changed entity in this EntityManager.

addEntity

(
  • entity
)
Entity

Attaches an entity to this EntityManager with an EntityState of 'Added'.

Parameters:

  • entity Entity

    The entity to add.

Returns:

Entity:

The added entity.

Example:

// assume em1 is an EntityManager containing a number of existing entities.
var custType = em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.addEntity(cust1);

Note that this is the same as using 'attachEntity' with an EntityState of 'Added'.

// assume em1 is an EntityManager containing a number of existing entities.
var custType = em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.attachEntity(cust1, EntityState.Added);

attachEntity

(
  • entity
  • [entityState=EntityState.Unchanged]
  • [mergeStrategy=MergeStrategy.Disallowed]
)
Entity

Attaches an entity to this EntityManager with a specified EntityState.

Parameters:

  • entity Entity

    The entity to add.

  • [entityState=EntityState.Unchanged] EntityState optional

    The EntityState of the newly attached entity. If omitted this defaults to EntityState.Unchanged.

  • [mergeStrategy=MergeStrategy.Disallowed] MergeStrategy optional

    How the specified entity should be merged into the EntityManager if this EntityManager already contains an entity with the same key.

Returns:

Entity:

The attached entity.

Example:

// assume em1 is an EntityManager containing a number of existing entities.
var custType = em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.attachEntity(cust1, EntityState.Added);

clear

()

Clears this EntityManager's cache but keeps all other settings. Note that this method is not as fast as creating a new EntityManager via 'new EntityManager'. This is because clear actually detaches all of the entities from the EntityManager.

Example:

// assume em1 is an EntityManager containing a number of existing entities.
em1.clear();
// em1 is will now contain no entities, but all other setting will be maintained.

createEmptyCopy

() EntityManager

Creates an empty copy of this EntityManager

Returns:

EntityManager:

A new EntityManager.

Example:

// assume em1 is an EntityManager containing a number of existing entities.
var em2 = em1.createEmptyCopy();
// em2 is a new EntityManager with all of em1's settings
// but no entities.

createEntity

(
  • entityType
  • [initialValues=null]
  • [entityState=EntityState.Added]
  • [mergeStrategy=MergeStrategy.Disallowed]
)
Entity

Creates a new entity of a specified type and optionally initializes it. By default the new entity is created with an EntityState of Added but you can also optionally specify an EntityState. An EntityState of 'Detached' will insure that the entity is created but not yet added to the EntityManager.

Parameters:

  • entityType String | EntityType

    The EntityType or the name of the type for which an instance should be created.

  • [initialValues=null] Config object optional
    • Configuration object of the properties to set immediately after creation.
  • [entityState=EntityState.Added] EntityState optional
    • The EntityState of the entity after being created and added to this EntityManager.
  • [mergeStrategy=MergeStrategy.Disallowed] MergeStrategy optional
    • How to handle conflicts if an entity with the same key already exists within this EntityManager.

Returns:

Entity:

A new Entity of the specified type.

Example:

// assume em1 is an EntityManager containing a number of preexisting entities.
// create and add an entity;
var emp1 = em1.createEntity("Employee");
// create and add an initialized entity;
var emp2 = em1.createEntity("Employee", { lastName: Smith", firstName: "John" });
// create and attach (not add) an initialized entity
var emp3 = em1.createEntity("Employee", { id: 435, lastName: Smith", firstName: "John" }, EntityState.Unchanged);
// create but don't attach an entity;
var emp4 = em1.createEntity("Employee", { id: 435, lastName: Smith", firstName: "John" }, EntityState.Detached);

detachEntity

(
  • entity
)
Boolean

Detaches an entity from this EntityManager.

Parameters:

  • entity Entity

    The entity to detach.

Returns:

Boolean:

Whether the entity could be detached. This will return false if the entity is already detached or was never attached.

Example:

// assume em1 is an EntityManager containing a number of existing entities.
// assume cust1 is a customer Entity previously attached to em1
em1.detachEntity(cust1);
// em1 will now no longer contain cust1 and cust1 will have an 
// entityAspect.entityState of EntityState.Detached

executeQuery

(
  • query
  • [callback]
  • [errorCallback]
)
Promise async

Executes the specified query.

Parameters:

  • query EntityQuery | String

    The EntityQuery or OData query string to execute.

  • [callback] Function optional

    Function called on success.

    successFunction([data])
    • data Object
      • results Array of Entity
      • query EntityQuery
        The original query
      • entityManager EntityManager
        The EntityManager.
      • httpResponse HttpResponse
        The HttpResponse returned from the server.
      • inlineCount Integer
        Only available if 'inlineCount(true)' was applied to the query. Returns the count of items that would have been returned by the query before applying any skip or take operators, but after any filter/where predicates would have been applied.
  • [errorCallback] Function optional

    Function called on failure.

    failureFunction([error])
    • [error] Error optional

      Any error that occured wrapped into an Error object.

      • [query] optional
        The query that caused the error.
      • [entityManager] optional
        The query that caused the error.
      • [httpResponse] HttpResponse optional
        The HttpResponse returned from the server.

Returns:

Promise:

Promise

promiseData.results {Array of Entity}
promiseData.query {EntityQuery} The original query
promiseData.entityManager {EntityManager} The EntityManager.
promiseData.httpResponse {HttpResponse} The  HttpResponse returned from the server.
promiseData.inlineCount {Integer} Only available if 'inlineCount(true)' was applied to the query.  Returns the count of 
items that would have been returned by the query before applying any skip or take operators, but after any filter/where predicates
would have been applied.

Example:

This method can be called using a 'promises' syntax ( recommended)

    var em = new EntityManager(serviceName);
    var query = new EntityQuery("Orders");
    em.executeQuery(query)
    .then( function(data) {
        var orders = data.results;
        ... query results processed here
    }).fail( function(err) {
        ... query failure processed here
    });

or with callbacks

    var em = new EntityManager(serviceName);
    var query = new EntityQuery("Orders");
    em.executeQuery(query,
    function(data) {
        var orders = data.results;
        ... query results processed here
    },
    function(err) {
        ... query failure processed here
    });

Either way this method is the same as calling the The EntityQuery 'execute' method.

    var em = new EntityManager(serviceName);
    var query = new EntityQuery("Orders").using(em);
    query.execute()
    .then( function(data) {
        var orders = data.results;
        ... query results processed here
    }).fail( function(err) {
        ... query failure processed here
    });

executeQueryLocally

(
  • query
)
Array of Entity

Executes the specified query against this EntityManager's local cache.

Parameters:

Returns:

Array of Entity:

Array of entities from cache that satisfy the query

Example:

Because this method is executed immediately there is no need for a promise or a callback

    var em = new EntityManager(serviceName);
    var query = new EntityQuery("Orders");
    var orders = em.executeQueryLocally(query);

Note that this can also be accomplished using the 'executeQuery' method with a FetchStrategy of FromLocalCache and making use of the Promise or callback

    var em = new EntityManager(serviceName);
    var query = new EntityQuery("Orders").using(FetchStrategy.FromLocalCache);
    em.executeQuery(query)
    .then( function(data) {
        var orders = data.results;
        ... query results processed here
    }).fail( function(err) {
        ... query failure processed here
    });

exportEntities

(
  • [entities]
  • [includeMetadata
)
String

Exports an entire EntityManager or just selected entities into a serialized string for external storage.

Parameters:

  • [entities] Array of entities optional

    The entities to export; all entities are exported if this is omitted or null

  • [includeMetadata Boolean

    = true] Whether to include metadata in the export; the default is true

Returns:

String:

A serialized version of the exported data.

Example:

This method can be used to take a snapshot of an EntityManager that can be either stored offline or held memory. This snapshot can be restored or merged into an another EntityManager at some later date.

// assume em1 is an EntityManager containing a number of existing entities.
var bundle = em1.exportEntities();
// can be stored via the web storage api
window.localStorage.setItem("myEntityManager", bundle);
// assume the code below occurs in a different session.
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
var em2 = new EntityManager({ 
    serviceName: em1.serviceName, 
    metadataStore: em1.metadataStore 
});
em2.importEntities(bundleFromStorage);
// em2 will now have a complete copy of what was in em1

You can also control exactly which entities are exported.

// assume entitiesToExport is an array of entities to export.
var bundle = em1.exportEntities(entitiesToExport);
// assume em2 is another entityManager containing some of the same entities possibly with modifications.
em2.importEntities(bundle, { mergeStrategy: MergeStrategy.PreserveChanges} );

fetchEntityByKey

(
  • typeName
  • keyValues
  • checkLocalCacheFirst
)
Promise async

Attempts to fetch an entity from the server by its key with an option to check the local cache first. Note the this EntityManager's queryOptions.mergeStrategy will be used to merge any server side entity returned by this method.

Parameters:

  • typeName EntityType | String

    The EntityType or EntityType name for this key.

  • keyValues Object | Array of Object

    The values for this key - will usually just be a single value; an array is only needed for multipart keys.

  • checkLocalCacheFirst Boolean=false

    Whether to check this EntityManager first before going to the server. By default, the query will NOT do this.

Returns:

Promise:
promiseData.entity {Object} The entity returned or null
promiseData.entityKey {EntityKey} The entityKey of the entity to fetch.
promiseData.fromCache {Boolean} Whether this entity was fetched from the server or was found in the local cache.

Example:

// assume em1 is an EntityManager containing a number of preexisting entities. 
em1.fetchEntityByKey("Employee", 1).then(function(result) {
    var employee = result.entity;
    var entityKey = result.entityKey;
    var fromCache = result.fromCache;
});

fetchEntityByKey - overload

(
  • entityKey
  • checkLocalCacheFirst
)
Promise async

Attempts to fetch an entity from the server by its EntityKey with an option to check the local cache first.

Parameters:

  • entityKey EntityKey

    The EntityKey of the Entity to be located.

  • checkLocalCacheFirst Boolean=false

    Whether to check this EntityManager first before going to the server. By default, the query will NOT do this.

Returns:

Promise:
promiseData.entity {Object} The entity returned or null
promiseData.entityKey {EntityKey} The entityKey of the entity to fetch.
promiseData.fromCache {Boolean} Whether this entity was fetched from the server or was found in the local cache.

Example:

// assume em1 is an EntityManager containing a number of preexisting entities. 
var employeeType = em1.metadataStore.getEntityType("Employee");
var employeeKey = new EntityKey(employeeType, 1);
em1.fetchEntityByKey(employeeKey).then(function(result) {
    var employee = result.entity;
    var entityKey = result.entityKey;
    var fromCache = result.fromCache;
});

fetchMetadata

(
  • [callback]
  • [errorCallback]
)
Promise async

Fetches the metadata associated with the EntityManager's current 'serviceName'. This call occurs internally before the first query to any service if the metadata hasn't already been loaded.

Parameters:

  • [callback] Function optional

    Function called on success.

    successFunction([schema])
    • [schema] Object optional

      The raw Schema object from metadata provider - Because this schema will differ depending on the metadata provider it is usually better to access metadata via the 'metadataStore' property of the EntityManager after this method's Promise or callback completes.

  • [errorCallback] Function optional

    Function called on failure.

    failureFunction([error])
    • [error] Error optional

      Any error that occured wrapped into an Error object.

Returns:

Promise:

Promise

promiseData.schema {Object} The raw Schema object from metadata provider - Because this schema will differ depending on the metadata provider
it is usually better to access metadata via the 'metadataStore' property of the EntityManager instead of using this 'raw' data.

Example:

Usually you will not actually process the results of a fetchMetadata call directly, but will instead ask for the metadata from the EntityManager after the fetchMetadata call returns.

    var em1 = new EntityManager( "breeze/NorthwindIBModel");
    em1.fetchMetadata()
    .then(function() {
        var metadataStore = em1.metadataStore;
        // do something with the metadata
    }
    .fail(function(exception) {
        // handle exception here
    };

findEntityByKey

(
  • entityKey
)
Entity deprecated

Defined in ..\..\src\a50_entityManager.js:1217

Deprecated: - use getEntityByKey instead

Attempts to locate an entity within this EntityManager by its EntityKey.

Parameters:

Returns:

Entity:

An Entity or null;

Example:

// assume em1 is an EntityManager containing a number of preexisting entities. 
var employeeType = em1.metadataStore.getEntityType("Employee");
var employeeKey = new EntityKey(employeeType, 1);
var employee = em1.findEntityByKey(employeeKey);
// employee will either be an entity or null.

generateTempKeyValue

(
  • entity
)
Object

Generates a temporary key for the specified entity. This is used to insure that newly created entities have unique keys and to register that these keys are temporary and need to be automatically replaced with 'real' key values once these entities are saved.

The EntityManager.keyGeneratorCtor property is used internally by this method to actually generate the keys - See the ~keyGenerator-interface interface description to see how a custom key generator can be plugged in.

Parameters:

  • entity Entity

    The Entity to generate a key for.

Returns:

Object:

The new key value

Example:

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var custumer = custType.createEntity();
var customerId = em.generateTempKeyValue(custumer);
// The 'customer' entity 'CustomerID' property is now set to a newly generated unique id value
// This property will change again after a successful save of the 'customer' entity.

em1.saveChanges()
    .then( function( data) {
        var sameCust1 = data.results[0];
        // cust1 === sameCust1;
        // but cust1.getProperty("CustomerId") != customerId
        // because the server will have generated a new id 
        // and the client will have been updated with this 
        // new id.
    })

getChanges

(
  • [entityTypes]
)
Array of Entity

Returns a array of all changed entities of the specified EntityTypes. A 'changed' Entity has has an EntityState of either Added, Modified or Deleted.

Parameters:

  • [entityTypes] String | Array of String | EntityType | Array of EntityType optional

    The EntityTypes for which 'changed' entities will be found. If this parameter is omitted, all EntityTypes are searched. String parameters are treated as EntityType names.

Returns:

Array of Entity:

Array of Entities

Example:

This method can be used to get all of the changed entities within an EntityManager

// assume em1 is an EntityManager containing a number of preexisting entities. 
var changedEntities = em1.getChanges();

or you can specify that you only want the changes on a specific EntityType

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var changedCustomers = em1.getChanges(custType);

or to a collection of EntityTypes

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var orderType = em1.metadataStore.getEntityType("Order");
var changedCustomersAndOrders = em1.getChanges([custType, orderType]);

getEntities

(
  • [entityTypes]
  • [entityState]
)
Array of Entity

Returns a array of all entities of the specified EntityTypes with the specified EntityStates.

Parameters:

  • [entityTypes] String | Array of String | EntityType | Array of EntityType optional

    The EntityTypes for which entities will be found. If this parameter is omitted, all EntityTypes are searched. String parameters are treated as EntityType names.

  • [entityState] EntityState | Array of EntityState optional

    The EntityStates for which entities will be found. If this parameter is omitted, entities of all EntityStates are returned.

Returns:

Array of Entity:

Array of Entities

Example:

This method can be used to get all of the entities within an EntityManager

// assume em1 is an EntityManager containing a number of preexisting entities. 
var entities = em1.getEntities();

or you can specify that you only want the changes on a specific EntityType

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var customers = em1.getEntities(custType);

or to a collection of EntityTypes

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var orderType = em1.metadataStore.getEntityType("Order");
var customersAndOrders = em1.getChanges([custType, orderType]);

You can also ask for entities with a particular EntityState or EntityStates.

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var orderType = em1.metadataStore.getEntityType("Order");
var addedCustomersAndOrders = em1.getEntities([custType, orderType], EntityState.Added);

getEntityByKey

(
  • typeName
  • keyValues
)
Entity

Attempts to locate an entity within this EntityManager by its key.

Parameters:

  • typeName EntityType | String

    The EntityType or EntityType name for this key.

  • keyValues Object | Array of Object

    The values for this key - will usually just be a single value; an array is only needed for multipart keys.

Returns:

Entity:

An Entity or null;

Example:

// assume em1 is an EntityManager containing a number of preexisting entities. 
var employee = em1.getEntityByKey("Employee", 1);
// employee will either be an entity or null.

getEntityByKey - overload

(
  • entityKey
)
Entity

Attempts to locate an entity within this EntityManager by its EntityKey.

Parameters:

Returns:

Entity:

An Entity or null;

Example:

// assume em1 is an EntityManager containing a number of preexisting entities. 
var employeeType = em1.metadataStore.getEntityType("Employee");
var employeeKey = new EntityKey(employeeType, 1);
var employee = em1.getEntityByKey(employeeKey);
// employee will either be an entity or null.

hasChanges

(
  • [entityTypes]
)
Boolean

Returns whether there are any changed entities of the specified EntityTypes. A 'changed' Entity has has an EntityState of either Added, Modified or Deleted.

Parameters:

  • [entityTypes] String | Array of String | EntityType | Array of EntityType optional

    The EntityTypes for which 'changed' entities will be found. If this parameter is omitted, all EntityTypes are searched. String parameters are treated as EntityType names.

Returns:

Boolean:

Whether there were any changed entities.

Example:

This method can be used to determine if an EntityManager has any changes

// assume em1 is an EntityManager containing a number of preexisting entities. 
if ( em1.hasChanges() {
    // do something interesting
}

or if it has any changes on to a specific EntityType

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
if ( em1.hasChanges(custType) {
    // do something interesting
}

or to a collection of EntityTypes

// assume em1 is an EntityManager containing a number of preexisting entities. 
var custType = em1.metadataStore.getEntityType("Customer");
var orderType = em1.metadataStore.getEntityType("Order");
if ( em1.hasChanges( [custType, orderType]) {
    // do something interesting
}

importEntities

(
  • exportedString
  • [config]
  • [config.metadataVersionFn}
)
EntityManager static

Creates a new EntityManager and imports a previously exported result into it.

Parameters:

  • exportedString String

    The result of a previous 'exportEntities' call.

  • [config] Object optional

    A configuration object.

  • [config.metadataVersionFn} Function

    A function that takes two arguments ( the current metadataVersion and the imported store's 'name'} and may be used to perform version checking.

Returns:

EntityManager:

A new EntityManager. Note that the return value of this method call is different from that provided by the same named method on an EntityManager instance. Use that method if you need additional information regarding the imported entities.

Example:

// assume em1 is an EntityManager containing a number of preexisting entities.
var bundle = em1.exportEntities();
// can be stored via the web storage api
window.localStorage.setItem("myEntityManager", bundle);
// assume the code below occurs in a different session.
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
// and imported
var em2 = EntityManager.importEntities(bundleFromStorage);
// em2 will now have a complete copy of what was in em1

importEntities

(
  • exportedString
  • [config]
  • [config.metadataVersionFn}
)
Object

Imports a previously exported result into this EntityManager.

Parameters:

  • exportedString String | Json

    The result of a previous 'export' call.

  • [config] Object optional

    A configuration object.

  • [config.metadataVersionFn} Function

    A function that takes two arguments ( the current metadataVersion and the imported store's 'name'} and may be used to perform version checking.

Returns:

Object:

result

result.entities {Array of Entities} The entities that were imported.
result.tempKeyMap {Object} Mapping from original EntityKey in the import bundle to its corresponding EntityKey in this EntityManager.

Example:

This method can be used to make a complete copy of any previously created entityManager, even if created in a previous session and stored in localStorage. The static version of this method performs a very similar process.

// assume em1 is an EntityManager containing a number of existing entities.
var bundle = em1.exportEntities();
// bundle can be stored in window.localStorage or just held in memory.
var em2 = new EntityManager({ 
    serviceName: em1.serviceName, 
    metadataStore: em1.metadataStore 
});
em2.importEntities(bundle);
// em2 will now have a complete copy of what was in em1

It can also be used to merge the contents of a previously created EntityManager with an existing EntityManager with control over how the two are merged.

var bundle = em1.exportEntities();
// assume em2 is another entityManager containing some of the same entities possibly with modifications.
em2.importEntities(bundle, { mergeStrategy: MergeStrategy.PreserveChanges} );
// em2 will now contain all of the entities from both em1 and em2.  Any em2 entities with previously 
// made modifications will not have been touched, but all other entities from em1 will have been imported.

rejectChanges

() Array of Entity

Rejects (reverses the effects) all of the additions, modifications and deletes from this EntityManager. Calls EntityAspect.rejectChanges on every changed entity in this EntityManager.

Returns:

Array of Entity:

The entities whose changes were rejected. These entities will all have EntityStates of either 'Unchanged' or 'Detached'

Example:

// assume em1 is an EntityManager containing a number of preexisting entities.
var entities = em1.rejectChanges();

saveChanges

(
  • [entities]
  • [saveOptions]
  • [callback]
  • [errorCallback]
)
Promise async

Saves either a list of specified entities or all changed entities within this EntityManager. If there are no changes to any of the entities specified then there will be no server side call made but a valid 'empty' saveResult will still be returned.

Parameters:

  • [entities] Array of Entity optional

    The list of entities to save.
    Every entity in that list will be sent to the server, whether changed or unchanged, as long as it is attached to this EntityManager. If this parameter is omitted, null or empty (the usual case), every entity with pending changes in this EntityManager will be saved.

  • [saveOptions] SaveOptions optional

    SaveOptions for the save - will default to EntityManager/saveOptions if null.

  • [callback] Function optional

    Function called on success.

    successFunction([saveResult])
    • [saveResult] Object optional
      • [entities] Array of Entity optional
        The saved entities - with any temporary keys converted into 'real' keys. These entities are actually references to entities in the EntityManager cache that have been updated as a result of the save.
      • [keyMappings] Array of keyMappings optional
        Each keyMapping has the following properties: 'entityTypeName', 'tempValue' and 'realValue'
      • [httpResponse] HttpResponse optional
        The raw HttpResponse returned from the server.
  • [errorCallback] Function optional

    Function called on failure.

    failureFunction([error])
    • [error] Error optional

      Any error that occured wrapped into an Error object.

      • [entityErrors] Array of server side errors optional
        These are typically validation errors but are generally any error that can be easily isolated to a single entity.
      • [httpResponse] HttpResponse optional
        The raw HttpResponse returned from the server.
      • [saveResult] Object optional
        Some dataservice adapters return a 'saveResult' object when the failing save operation is non-transactional meaning some entities could be saved while others were not. The 'saveResult' object identifies both that entities that were saved (with their keyMapping) and that entities that were not saved (with their errors).

Returns:

Promise:

Promise

Example:

Often we will be saving all of the entities within an EntityManager that are either added, modified or deleted and we will let the 'saveChanges' call determine which entities these are.

// assume em1 is an EntityManager containing a number of preexisting entities. 
// This could include added, modified and deleted entities.
em.saveChanges().then(function(saveResult) {
    var savedEntities = saveResult.entities;
    var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
    // e is any exception that was thrown.
});

But we can also control exactly which entities to save and can specify specific SaveOptions

// assume entitiesToSave is an array of entities to save.
var saveOptions = new SaveOptions({ allowConcurrentSaves: true });
em.saveChanges(entitiesToSave, saveOptions).then(function(saveResult) {
    var savedEntities = saveResult.entities;
    var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
    // e is any exception that was thrown.
});

Callback methods can also be used

em.saveChanges(entitiesToSave, null, 
    function(saveResult) {
        var savedEntities = saveResult.entities;
        var keyMappings = saveResult.keyMappings;
    }, function (e) {
        // e is any exception that was thrown.
    }
);

setProperties

(
  • config
)

General purpose property set method. Any of the properties documented below may be set.

Parameters:

Example:

    // assume em1 is a previously created EntityManager
    // where we want to change some of its settings.
    em1.setProperties( {
        serviceName: "breeze/foo"
    });

Properties

dataService

DataService

The DataService name associated with this EntityManager.

readOnly

keyGeneratorCtor

KeyGenerator constructor

The KeyGenerator constructor associated with this EntityManager.

readOnly

metadataStore

MetadataStore

The MetadataStore associated with this EntityManager.

__readOnly__

queryOptions

QueryOptions

The QueryOptions associated with this EntityManager.

readOnly

saveOptions

SaveOptions

The SaveOptions associated with this EntityManager.

readOnly

serviceName

String

The service name associated with this EntityManager.

readOnly

validationOptions

ValidationOptions

The ValidationOptions associated with this EntityManager.

readOnly

Events

entityChanged

An Event that fires whenever a change to any entity in this EntityManager occurs.

Event Payload:

  • entityAction EntityAction

    The EntityAction that occured.

  • entity Object

    The entity that changed. If this is null, then all entities in the entityManager were affected.

  • args Object

    Additional information about this event. This will differ based on the entityAction.

Example:

var em = new EntityManager( {serviceName: "breeze/NorthwindIBModel" });
em.entityChanged.subscribe(function(changeArgs) {
    // This code will be executed any time any entity within the entityManager is added, modified, deleted or detached for any reason. 
    var action = changeArgs.entityAction;
    var entity = changeArgs.entity;
    // .. do something to this entity when it is changed.
});

});

hasChangesChanged

An Event that fires whenever an EntityManager transitions to or from having changes.

Event Payload:

  • entityManager EntityManager

    The EntityManager whose 'hasChanges' status has changed.

  • hasChanges Boolean

    Whether or not this EntityManager has changes.

Example:

var em = new EntityManager( {serviceName: "breeze/NorthwindIBModel" });
em.hasChangesChanged.subscribe(function(args) {
    var hasChangesChanged = args.hasChanges;
    var entityManager = args.entityManager;
});

});

validationErrorsChanged

An Event that fires whenever validationErrors change for any entity in this EntityManager.

Event Payload:

  • entity Entity

    The entity on which the validation errors have been added or removed.

  • added Array of ValidationError

    An array containing any newly added ValidationErrors

  • removed Array of ValidationError

    An array containing any newly removed ValidationErrors. This is those errors that have been 'fixed'

Example:

var em = new EntityManager( {serviceName: "breeze/NorthwindIBModel" });
em.validationErrorsChanged.subscribe(function(changeArgs) {
    // This code will be executed any time any entity within the entityManager experiences a change to its validationErrors collection. 
    function (validationChangeArgs) {
        var entity == validationChangeArgs.entity; 
        var errorsAdded = validationChangeArgs.added;
        var errorsCleared = validationChangeArgs.removed;
        // ... do something interesting with the order.
    });
});

});