EntityManager Class
Instances of the EntityManager contain and manage collections of entities, either retrieved from a backend datastore or created on the client.
Item Index
Methods
- <ctor> EntityManager
- acceptChanges
- addEntity
- attachEntity
- clear
- createEmptyCopy
- createEntity
- detachEntity
- executeQuery
- executeQueryLocally
- exportEntities
- fetchEntityByKey
- fetchEntityByKey - overload
- fetchMetadata
- findEntityByKey deprecated
- generateTempKeyValue
- getChanges
- getEntities
- getEntityByKey
- getEntityByKey - overload
- hasChanges
- importEntities static
- importEntities
- rejectChanges
- saveChanges
- setProperties
Properties
Methods
<ctor> EntityManager
-
[config]
Parameters:
-
[config]
Object | String optionalConfiguration settings or a service name.
-
[serviceName]
String optional -
[dataService]
DataService optionalAn 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
Attaches an entity to this EntityManager with an EntityState of 'Added'.
Parameters:
-
entity
EntityThe entity to add.
Returns:
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]
Attaches an entity to this EntityManager with a specified EntityState.
Parameters:
-
entity
EntityThe entity to add.
-
[entityState=EntityState.Unchanged]
EntityState optionalThe EntityState of the newly attached entity. If omitted this defaults to EntityState.Unchanged.
-
[mergeStrategy=MergeStrategy.Disallowed]
MergeStrategy optionalHow the specified entity should be merged into the EntityManager if this EntityManager already contains an entity with the same key.
Returns:
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:
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]
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 | EntityTypeThe 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:
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
Detaches an entity from this EntityManager.
Parameters:
-
entity
EntityThe entity to detach.
Returns:
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]
Executes the specified query.
Parameters:
-
query
EntityQuery | StringThe EntityQuery or OData query string to execute.
-
[callback]
Function optionalFunction called on success.
successFunction([data])
-
data
Object-
results
Array of Entity -
query
EntityQueryThe original query -
entityManager
EntityManagerThe EntityManager. -
httpResponse
HttpResponseThe HttpResponse returned from the server. -
inlineCount
IntegerOnly 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 optionalFunction called on failure.
failureFunction([error])
-
[error]
Error optionalAny error that occured wrapped into an Error object.
-
[query]
optionalThe query that caused the error. -
[entityManager]
optionalThe query that caused the error. -
[httpResponse]
HttpResponse optionalThe HttpResponse returned from the server.
-
-
Returns:
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
Executes the specified query against this EntityManager's local cache.
Parameters:
-
query
EntityQueryThe EntityQuery to execute.
Returns:
Array of Entities
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
Exports an entire EntityManager or just selected entities into a serialized string for external storage.
Parameters:
-
[entities]
Array of entities optionalThe 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:
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
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 | StringThe EntityType or EntityType name for this key.
-
keyValues
Object | Array of ObjectThe values for this key - will usually just be a single value; an array is only needed for multipart keys.
-
checkLocalCacheFirst
Boolean=falseWhether to check this EntityManager first before going to the server. By default, the query will NOT do this.
Returns:
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
Attempts to fetch an entity from the server by its EntityKey with an option to check the local cache first.
Parameters:
Returns:
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]
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 optionalFunction called on success.
successFunction([schema])
-
[schema]
Object optionalThe 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 optionalFunction called on failure.
failureFunction([error])
-
[error]
Error optionalAny error that occured wrapped into an Error object.
-
Returns:
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
Attempts to locate an entity within this EntityManager by its EntityKey.
Returns:
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
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
EntityThe Entity to generate a key for.
Returns:
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]
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 optionalThe 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 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]
Returns a array of all entities of the specified EntityTypes with the specified EntityStates.
Parameters:
-
[entityTypes]
String | Array of String | EntityType | Array of EntityType optionalThe 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 optionalThe EntityStates for which entities will be found. If this parameter is omitted, entities of all EntityStates are returned.
Returns:
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
Attempts to locate an entity within this EntityManager by its key.
Parameters:
-
typeName
EntityType | StringThe EntityType or EntityType name for this key.
-
keyValues
Object | Array of ObjectThe values for this key - will usually just be a single value; an array is only needed for multipart keys.
Returns:
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
Attempts to locate an entity within this EntityManager by its EntityKey.
Returns:
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]
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 optionalThe 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:
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}
Creates a new EntityManager and imports a previously exported result into it.
Parameters:
-
exportedString
StringThe result of a previous 'exportEntities' call.
-
[config]
Object optionalA configuration object.
-
[mergeStrategy]
MergeStrategy optionalA MergeStrategy to use when merging into an existing EntityManager.
-
-
[config.metadataVersionFn}
FunctionA function that takes two arguments ( the current metadataVersion and the imported store's 'name'} and may be used to perform version checking.
Returns:
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}
Imports a previously exported result into this EntityManager.
Parameters:
-
exportedString
String | JsonThe result of a previous 'export' call.
-
[config]
Object optionalA configuration object.
-
[mergeStrategy]
MergeStrategy optionalA MergeStrategy to use when merging into an existing EntityManager.
-
-
[config.metadataVersionFn}
FunctionA function that takes two arguments ( the current metadataVersion and the imported store's 'name'} and may be used to perform version checking.
Returns:
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:
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]
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 optionalThe 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 optionalSaveOptions for the save - will default to EntityManager/saveOptions if null.
-
[callback]
Function optionalFunction called on success.
successFunction([saveResult])
-
[saveResult]
Object optional-
[entities]
Array of Entity optionalThe 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 optionalEach keyMapping has the following properties: 'entityTypeName', 'tempValue' and 'realValue' -
[httpResponse]
HttpResponse optionalThe raw HttpResponse returned from the server.
-
-
-
[errorCallback]
Function optionalFunction called on failure.
failureFunction([error])
-
[error]
Error optionalAny error that occured wrapped into an Error object.
-
[entityErrors]
Array of server side errors optionalThese are typically validation errors but are generally any error that can be easily isolated to a single entity. -
[httpResponse]
HttpResponse optionalThe raw HttpResponse returned from the server. -
[saveResult]
Object optionalSome 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
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:
-
config
Object-
[serviceName]
String optional -
[dataService]
DataService optional -
[queryOptions]
QueryOptions optional -
[saveOptions]
SaveOptions optional -
[validationOptions]
ValidationOptions optional -
[keyGeneratorCtor]
Function optional
-
Example:
// assume em1 is a previously created EntityManager
// where we want to change some of its settings.
em1.setProperties( {
serviceName: "breeze/foo"
});
Properties
keyGeneratorCtor
KeyGenerator constructor
The KeyGenerator constructor 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
EntityActionThe EntityAction that occured.
-
entity
ObjectThe entity that changed. If this is null, then all entities in the entityManager were affected.
-
args
ObjectAdditional 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
EntityManagerThe EntityManager whose 'hasChanges' status has changed.
-
hasChanges
BooleanWhether 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
EntityThe entity on which the validation errors have been added or removed.
-
added
Array of ValidationErrorAn array containing any newly added ValidationErrors
-
removed
Array of ValidationErrorAn 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.
});
});
});