Skip to content

breeze-client / EntityManager

Class: EntityManager ​

Defined in: src/manager/entity-manager.ts:419

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

Extended by ​

Constructors ​

Constructor ​

new EntityManager(emConfig?): EntityManager

Defined in: src/manager/entity-manager.ts:581

EntityManager constructor.

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

ts
const entityManager = new EntityManager("breeze/NorthwindIBModel");

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

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

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

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

or

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

Parameters ​

emConfig? ​

string | EntityManagerConfig

Configuration settings or a service name.

Returns ​

EntityManager

Properties ​

dataService ​

dataService: DataService

Defined in: src/manager/entity-manager.ts:426

The DataService associated with this EntityManager. Read Only


entityChanged ​

entityChanged: BreezeEvent<EntityChangedEventArgs>

Defined in: src/manager/entity-manager.ts:470

A BreezeEvent that fires whenever a change to any entity in this EntityManager occurs. Read Only

Event Args ​

  • entityAction - The EntityAction that occured.
  • entity - The entity that changed. Undefined for EntityAction.Clear, which affects every entity in the manager.
  • args - Additional information about this event. This will differ based on the entityAction.
ts
const em = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
em.entityChanged.subscribe(changeArgs => {
    // This code will be executed any time any entity within the entityManager
    // is added, modified, deleted or detached for any reason.
    const action = changeArgs.entityAction;
    const entity = changeArgs.entity;
    // .. do something to this entity when it is changed.
});

Event ​


hasChangesChanged ​

hasChangesChanged: BreezeEvent<HasChangesChangedEventArgs>

Defined in: src/manager/entity-manager.ts:509

A BreezeEvent that fires whenever an EntityManager transitions to or from having changes. Read Only

Event Args ​

    • entityManager - The EntityManager whose 'hasChanges' status has changed.
    • hasChanges - Whether or not this EntityManager has changes.
ts
const em = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
em.hasChangesChanged.subscribe(args => {
    const hasChanges = args.hasChanges;
    const entityManager = args.entityManager;
});

Event ​


helper ​

helper: object

Defined in: src/manager/entity-manager.ts:531

Functions a DataServiceAdapter uses to build the save request: unwrapInstance turns an entity or complex object into a plain object with server property names, unwrapOriginalValues does the same for its original values, and unwrapChangedValues for the current values of its changed properties. For adapter authors; applications do not normally need it.

unwrapChangedValues ​

unwrapChangedValues: (entity, metadataStore, transformFn) => Record<string, any>

The same, for the current values of an entity's changed properties.

Parameters ​
entity ​

Entity

metadataStore ​

MetadataStore

transformFn ​

(dp, val) => any

Returns ​

Record<string, any>

unwrapInstance ​

unwrapInstance: (structObj, transformFn?) => any

Turns an entity or complex object into a plain object keyed by server property names.

Parameters ​
structObj ​

StructuralObject

transformFn? ​

(dp, val) => any

Returns ​

any

unwrapOriginalValues ​

unwrapOriginalValues: (target, metadataStore, transformFn?) => Record<string, any>

The same, for the original values of an entity's changed properties.

Parameters ​
target ​

StructuralObject

metadataStore ​

MetadataStore

transformFn? ​

(dp, val) => any

Returns ​

Record<string, any>


isLoading ​

isLoading: boolean

Defined in: src/manager/entity-manager.ts:443

True while Breeze is loading entities into this manager - merging query or save results, or attaching or creating entities. While it is set, property changes do not mark entities Modified, are not validated, and raise no property-change events. Used by Breeze; applications do not normally need it.


isRejectingChanges ​

isRejectingChanges: boolean

Defined in: src/manager/entity-manager.ts:447

True while EntityAspect.rejectChanges restores an entity's original values, so that restoring them raises no property-change events. Used by Breeze; applications do not normally need it.


keyGenerator ​

keyGenerator: KeyGenerator

Defined in: src/manager/entity-manager.ts:434

The KeyGenerator associated with this EntityManager. Read Only


keyGeneratorCtor ​

keyGeneratorCtor: () => KeyGenerator

Defined in: src/manager/entity-manager.ts:436

The KeyGenerator constructor associated with this EntityManager. Read Only

Returns ​

KeyGenerator


metadataStore ​

metadataStore: MetadataStore

Defined in: src/manager/entity-manager.ts:438

The MetadataStore associated with this EntityManager. Read Only


queryOptions ​

queryOptions: QueryOptions

Defined in: src/manager/entity-manager.ts:428

The QueryOptions associated with this EntityManager. Read Only


saveOptions ​

saveOptions: SaveOptions

Defined in: src/manager/entity-manager.ts:430

The SaveOptions associated with this EntityManager. Read Only


serviceName ​

serviceName: string

Defined in: src/manager/entity-manager.ts:424

The service name associated with this EntityManager. Read Only


validationErrorsChanged ​

validationErrorsChanged: BreezeEvent<ValidationErrorsChangedEventArgs>

Defined in: src/manager/entity-manager.ts:492

An BreezeEvent that fires whenever validationErrors change for any entity in this EntityManager. Read Only

Event Args ​

    • entity - The entity on which the validation errors have been added or removed.
    • added - An array containing any newly added ValidationErrors
    • removed - An array containing any newly removed ValidationErrors. This is those errors that have been 'fixed'
ts
const em = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
em.validationErrorsChanged.subscribe(changeArgs => {
    // This code will be executed any time any entity within the entityManager
    // experiences a change to its validationErrors collection.
    const entity = changeArgs.entity;
    const errorsAdded = changeArgs.added;
    const errorsCleared = changeArgs.removed;
    // ... do something interesting with the entity.
});

Event ​


validationOptions ​

validationOptions: ValidationOptions

Defined in: src/manager/entity-manager.ts:432

The ValidationOptions associated with this EntityManager. Read Only

Methods ​

acceptChanges() ​

acceptChanges(): void

Defined in: src/manager/entity-manager.ts:771

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

Returns ​

void


addEntity() ​

addEntity<T>(entity): T

Defined in: src/manager/entity-manager.ts:1057

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

ts
// assume em1 is an EntityManager containing a number of existing entities.
const cust1 = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
em1.addEntity(cust1);     // returns cust1, a Customer

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

ts
// assume em1 is an EntityManager containing a number of existing entities.
const cust1 = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
em1.attachEntity(cust1, EntityState.Added);

Type Parameters ​

T ​

T extends Entity

Parameters ​

entity ​

T

The entity to add.

Returns ​

T

The added entity.


attachEntity() ​

attachEntity<T>(entity, entityState?, mergeStrategy?): T

Defined in: src/manager/entity-manager.ts:1073

Attaches an entity to this EntityManager with a specified EntityState.

ts
// assume em1 is an EntityManager containing a number of existing entities.
const cust1 = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
em1.attachEntity(cust1, EntityState.Added);     // returns cust1, a Customer

Type Parameters ​

T ​

T extends Entity

Parameters ​

entity ​

T

The entity to add.

entityState? ​

EntityState

(default=EntityState.Unchanged) The EntityState of the newly attached entity. If omitted this defaults to EntityState.Unchanged.

mergeStrategy? ​

MergeStrategy

(default = MergeStrategy.Disallowed) How the specified entity should be merged into the EntityManager if this EntityManager already contains an entity with the same key.

Returns ​

T

The attached entity.


clear() ​

clear(): void

Defined in: src/manager/entity-manager.ts:1009

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.

ts
// 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.

Returns ​

void


createEmptyCopy() ​

createEmptyCopy(): EntityManager

Defined in: src/manager/entity-manager.ts:1033

Creates an empty copy of this EntityManager but with the same DataService, MetadataStore, QueryOptions, SaveOptions, ValidationOptions, etc.

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

Returns ​

EntityManager

A new EntityManager.


createEntity() ​

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.

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
// create and add an entity. Passing the registered class types the result:
const emp1 = em1.createEntity(Employee);            // Employee
// create and add an initialized entity;
const emp2 = em1.createEntity(Employee, { lastName: "Smith", firstName: "John" });
// create and attach (not add) an initialized entity
const emp3 = em1.createEntity(Employee, { employeeID: 435, lastName: "Smith", firstName: "John" }, EntityState.Unchanged);
// create but don't attach an entity;
const emp4 = em1.createEntity(Employee, { employeeID: 435, lastName: "Smith", firstName: "John" }, EntityState.Detached);
// with the constructor, initialValues is checked: a property Employee does not declare,
// such as a misspelling, is a compile error rather than a value silently ignored
em1.createEntity(Employee, { lastNmae: "Smith" });   // error

// the type name and the EntityType both still work, and return Entity:
const emp5 = em1.createEntity("Employee", { lastName: "Smith" });

The constructor overload needs the class to have been registered with MetadataStore.registerEntityTypeCtor; that is what tells Breeze which type it stands for. An unregistered class throws. See the Typed entities guide.

Param ​

entityCtor

A constructor registered for the EntityType to create.

Param ​

typeName

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

Param ​

entityType

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

Param ​

initialValues

(default=null) Configuration object of the properties to set immediately after creation. With the constructor overload it is typed as InitialValues, so a property the class does not declare is a compile error.

Param ​

entityState

(default = EntityState.Added) The EntityState of the entity after being created and added to this EntityManager.

Param ​

mergeStrategy

(default = MergeStrategy.Disallowed) - How to handle conflicts if an entity with the same key already exists within this EntityManager.

Call Signature ​

createEntity<T>(entityCtor, initialValues?, entityState?, mergeStrategy?): T

Defined in: src/manager/entity-manager.ts:669

Type Parameters ​
T ​

T extends Entity

Parameters ​
entityCtor ​

() => T

initialValues? ​

InitialValues<T>

entityState? ​

EntityState

mergeStrategy? ​

MergeStrategy

Returns ​

T

Call Signature ​

createEntity(typeName, initialValues?, entityState?, mergeStrategy?): Entity

Defined in: src/manager/entity-manager.ts:670

Parameters ​
typeName ​

string

initialValues? ​

Object

entityState? ​

EntityState

mergeStrategy? ​

MergeStrategy

Returns ​

Entity

Call Signature ​

createEntity(entityType, initialValues?, entityState?, mergeStrategy?): Entity

Defined in: src/manager/entity-manager.ts:671

Parameters ​
entityType ​

EntityType

initialValues? ​

Object

entityState? ​

EntityState

mergeStrategy? ​

MergeStrategy

Returns ​

Entity


detachEntity() ​

detachEntity(entity): any

Defined in: src/manager/entity-manager.ts:1160

Detaches an entity from this EntityManager.

ts
// 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

Parameters ​

entity ​

Entity

The entity to detach.

Returns ​

any

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


executeQuery() ​

Executes the specified query. Async

ts
const em = new EntityManager(serviceName);
const query = EntityQuery.from(Order);
const data = await em.executeQuery(query);
const orders = data.results;   // Order[], because the query was built from the class

The callback and errorCallback arguments are deprecated. They still work, but the promise is the supported form and the callbacks will be removed in a future major version.

This method is the same as calling the EntityQuery 'execute' method.

ts
const em = new EntityManager(serviceName);
const data = await EntityQuery.from(Order).using(em).execute();
const orders = data.results;   // Order[]

Param ​

query

The EntityQuery or query string to execute.

Param ​

callback

Deprecated. Function called on success.

Param ​

errorCallback

Deprecated. Function called on failure.

Call Signature ​

executeQuery<T>(query): Promise<QueryResult<T>>

Defined in: src/manager/entity-manager.ts:1214

Type Parameters ​
T ​

T

Parameters ​
query ​

EntityQuery<T>

Returns ​

Promise<QueryResult<T>>

Call Signature ​

executeQuery(query): Promise<QueryResult<any>>

Defined in: src/manager/entity-manager.ts:1215

Parameters ​
query ​

string

Returns ​

Promise<QueryResult<any>>

Call Signature ​

executeQuery<T>(query, callback?, errorCallback?): Promise<QueryResult<T>>

Defined in: src/manager/entity-manager.ts:1217

Type Parameters ​
T ​

T

Parameters ​
query ​

EntityQuery<T>

callback? ​

QuerySuccessCallback

errorCallback? ​

QueryErrorCallback

Returns ​

Promise<QueryResult<T>>

Deprecated ​

Await the returned promise instead of passing callbacks.

Call Signature ​

executeQuery(query, callback?, errorCallback?): Promise<QueryResult<any>>

Defined in: src/manager/entity-manager.ts:1219

Parameters ​
query ​

string

callback? ​

QuerySuccessCallback

errorCallback? ​

QueryErrorCallback

Returns ​

Promise<QueryResult<any>>

Deprecated ​

Await the returned promise instead of passing callbacks.


executeQueryLocally() ​

executeQueryLocally<T>(query): T[]

Defined in: src/manager/entity-manager.ts:1295

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

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

ts
const em = new EntityManager(serviceName);
const query = EntityQuery.from(Order);
const orders = em.executeQueryLocally(query);   // Order[]

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

ts
const em = new EntityManager(serviceName);
const query = EntityQuery.from(Order).using(FetchStrategy.FromLocalCache);
const data = await em.executeQuery(query);
const orders = data.results;   // Order[]

Type Parameters ​

T ​

T

Parameters ​

query ​

EntityQuery<T>

The EntityQuery to execute.

Returns ​

T[]

Array of entities from cache that satisfy the query


exportEntities() ​

Exports selected entities, all entities of selected types, or an entire EntityManager cache.

This method takes a snapshot of an EntityManager that can be stored offline or held in memory. Use the EntityManager.importEntities method to restore or merge the snapshot into another EntityManager at some later time.

ts
// let em1 be an EntityManager containing a number of existing entities.
// export every entity in em1.
const bundle = em1.exportEntities() as string;
// save to the browser's local storage
window.localStorage.setItem("myEntityManager", bundle);
// later retrieve the export
const bundleFromStorage = window.localStorage.getItem("myEntityManager");
// import the retrieved export bundle into another manager
const em2 = em1.createEmptyCopy();
em2.importEntities(bundleFromStorage);
// em2 now has a complete, faithful copy of the entities that were in em1

You can also control exactly which entities are exported.

ts
// get em1's unsaved changes (an array) and export them.
const changes = em1.getChanges();
const bundle = em1.exportEntities(changes);
// merge these entities into em2 which may contains some of the same entities.
// do NOT overwrite the entities in em2 if they themselves have unsaved changes.
em2.importEntities(bundle, { mergeStrategy: MergeStrategy.PreserveChanges });

Metadata are included in an export by default. You may want to exclude the metadata especially if you're exporting just a few entities for local storage.

ts
const bundle = em1.exportEntities(arrayOfSelectedEntities, { includeMetadata: false }) as string;
window.localStorage.setItem("goodStuff", bundle);

You may still express this option as a boolean value although this older syntax is deprecated.

ts
// Exclude the metadata (deprecated syntax)
const bundle = em1.exportEntities(arrayOfSelectedEntities, false);

You can export all entities of one or more specified EntityTypes, by name.

ts
// Export all Customer and Employee entities (and also exclude metadata)
const bundle = em1.exportEntities(['Customer', 'Employee'], { includeMetadata: false });

All of the above examples return an export bundle as a string which is the default format. You can export the bundle as JSON if you prefer by setting the asString option to false.

ts
// Export all Customer and Employee entities as JSON and exclude the metadata
const bundle = em1.exportEntities(['Customer', 'Employee'],
                                  { asString: false, includeMetadata: false });
// store JSON bundle somewhere ... perhaps indexDb ... and later import as we do here.
em2.importEntities(bundle);

Param ​

entities

The entities to export, or the types of the entities to export - as registered classes, EntityTypes or type names. All entities are exported if this parameter is omitted or null.

Param ​

exportConfig

Export configuration options or a boolean

  • asString - (boolean) - If true (default), return export bundle as a string.
  • includeMetadata - (boolean) - If true (default), include metadata in the export bundle.

Call Signature ​

exportEntities(entities?, exportConfig?): string

Defined in: src/manager/entity-manager.ts:781

Parameters ​
entities? ​

ExportEntitiesArg

exportConfig? ​

boolean | { asString?: true; includeMetadata?: boolean; }

Returns ​

string

Call Signature ​

exportEntities(entities, exportConfig): Object

Defined in: src/manager/entity-manager.ts:782

Parameters ​
entities ​

ExportEntitiesArg | undefined

exportConfig ​
asString ​

false

includeMetadata? ​

boolean

Returns ​

Object

Call Signature ​

exportEntities(entities?, exportConfig?): string | Object

Defined in: src/manager/entity-manager.ts:783

Parameters ​
entities? ​

ExportEntitiesArg

exportConfig? ​

boolean | { asString?: boolean; includeMetadata?: boolean; }

Returns ​

string | Object


fetchEntityByKey() ​

Attempts to fetch an entity from the server by its EntityKey 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.

ts
// assume em1 is an EntityManager containing a number of preexisting entities,
// and that Employee is registered with its MetadataStore.
const result = await em1.fetchEntityByKey(Employee, 1);
const employee = result.entity;       // Employee | null
const entityKey = result.entityKey;
const fromCache = result.fromCache;
// look in the cache first, and query the server only if it is not there
const { entity } = await em1.fetchEntityByKey(Employee, 1, true);

A type name, an EntityType or an EntityKey also works; the result's entity is then a plain Entity.

ts
const result = await em1.fetchEntityByKey("Employee", 1);

Param ​

typeName

The EntityType name for this key.

Param ​

entityType

The EntityType for this key.

Param ​

keyValues

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

Param ​

entityKey

The EntityKey of the Entity to be located.

Param ​

checkLocalCacheFirst

(default = false) - Whether to check this EntityManager first before going to the server. By default, the query will NOT do this.

Call Signature ​

fetchEntityByKey<T>(entityCtor, keyValues, checkLocalCacheFirst?): Promise<EntityByKeyResult<T>>

Defined in: src/manager/entity-manager.ts:1611

Type Parameters ​
T ​

T extends Entity

Parameters ​
entityCtor ​

() => T

keyValues ​

any[] | KeyValue | KeyValues<T>

checkLocalCacheFirst? ​

boolean

Returns ​

Promise<EntityByKeyResult<T>>

Call Signature ​

fetchEntityByKey(typeName, keyValues, checkLocalCacheFirst?): Promise<IEntityByKeyResult>

Defined in: src/manager/entity-manager.ts:1612

Parameters ​
typeName ​

string

keyValues ​

any

checkLocalCacheFirst? ​

boolean

Returns ​

Promise<IEntityByKeyResult>

Call Signature ​

fetchEntityByKey(entityType, keyValues, checkLocalCacheFirst?): Promise<IEntityByKeyResult>

Defined in: src/manager/entity-manager.ts:1613

Parameters ​
entityType ​

EntityType

keyValues ​

any

checkLocalCacheFirst? ​

boolean

Returns ​

Promise<IEntityByKeyResult>

Call Signature ​

fetchEntityByKey(entityKey, checkLocalCacheFirst?): Promise<IEntityByKeyResult>

Defined in: src/manager/entity-manager.ts:1614

Parameters ​
entityKey ​

EntityKey

checkLocalCacheFirst? ​

boolean

Returns ​

Promise<IEntityByKeyResult>


fetchMetadata() ​

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. Async

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.

ts
const em1 = new EntityManager("breeze/NorthwindIBModel");
await em1.fetchMetadata();
const metadataStore = em1.metadataStore;
// do something with the metadata

Param ​

callback

Deprecated. Function called on success.

Param ​

errorCallback

Deprecated. Function called on failure.

Call Signature ​

fetchMetadata(dataService?): Promise<any>

Defined in: src/manager/entity-manager.ts:1174

Parameters ​
dataService? ​

DataService

Returns ​

Promise<any>

Call Signature ​

fetchMetadata(dataService, callback?, errorCallback?): Promise<any>

Defined in: src/manager/entity-manager.ts:1176

Parameters ​
dataService ​

DataService | undefined

callback? ​

Callback

errorCallback? ​

ErrorCallback

Returns ​

Promise<any>

Deprecated ​

Await the returned promise instead of passing callbacks.


findEntityByKey() ​

findEntityByKey(entityKey): Entity | null

Defined in: src/manager/entity-manager.ts:1669

[Deprecated] - Attempts to locate an entity within this EntityManager by its EntityKey.

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

Parameters ​

entityKey ​

EntityKey

The EntityKey of the Entity to be located.

Returns ​

Entity | null

An Entity or null;

Deprecated ​

Use getEntityByKey instead


generateTempKeyValue() ​

generateTempKeyValue(entity): any

Defined in: src/manager/entity-manager.ts:1695

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.

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const customer = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
const customerId = em1.generateTempKeyValue(customer);
// customer.customerID is now set to a newly generated unique id value.
// This property will change again after a successful save of the customer.
em1.addEntity(customer);
await em1.saveChanges();
// customer.customerID !== customerId, because the server will have generated
// a new id and the client will have been updated with this new id.

Parameters ​

entity ​

Entity

The Entity to generate a key for.

Returns ​

any

The new key value


getChanges() ​

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

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

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

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

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const changedCustomers = em1.getChanges(Customer);   // Customer[], from the registered class

or to a collection of EntityTypes, named or given as EntityTypes

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const changedCustomersAndOrders = em1.getChanges(["Customer", "Order"]);   // Entity[]

Param ​

entityTypes

The EntityType or EntityTypes for which 'changed' entities will be found.

Param ​

entityTypeNames

The EntityType name or names for which 'changed' entities will be found.

Call Signature ​

getChanges<T>(entityCtor): T[]

Defined in: src/manager/entity-manager.ts:1758

Type Parameters ​
T ​

T extends Entity

Parameters ​
entityCtor ​

() => T

Returns ​

T[]

Call Signature ​

getChanges<C>(entityCtors): InstanceType<C[number]>[]

Defined in: src/manager/entity-manager.ts:1760

Several types at once: getChanges([Customer, Order]) is (Customer | Order)[].

Type Parameters ​
C ​

C extends () => Entity[]

Parameters ​
entityCtors ​

[...C[]]

Returns ​

InstanceType<C[number]>[]

Call Signature ​

getChanges(): Entity[]

Defined in: src/manager/entity-manager.ts:1761

Returns ​

Entity[]

Call Signature ​

getChanges(entityTypeNames): Entity[]

Defined in: src/manager/entity-manager.ts:1762

Parameters ​
entityTypeNames ​

string | string[]

Returns ​

Entity[]

Call Signature ​

getChanges(entityTypes): Entity[]

Defined in: src/manager/entity-manager.ts:1763

Parameters ​
entityTypes ​

EntityType | EntityType[]

Returns ​

Entity[]


getEntities() ​

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

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

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

or you can specify that you only want the entities of a specific EntityType

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const customers = em1.getEntities(Customer);          // Customer[]

or of a collection of EntityTypes, named or given as EntityTypes

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const customersAndOrders = em1.getEntities(["Customer", "Order"]);   // Entity[]

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

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const addedCustomers = em1.getEntities(Customer, EntityState.Added);   // Customer[]
const addedOrModifiedOrders = em1.getEntities(Order, [EntityState.Added, EntityState.Modified]);

Param ​

entityTypeName

The EntityType name or names for which entities will be found. If this parameter is omitted, all EntityTypes are searched.

Param ​

entityTypes

The EntityType or EntityTypes for which entities will be found. If this parameter is omitted, all EntityTypes are searched.

Param ​

entityStates

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

Call Signature ​

getEntities<T>(entityCtor, entityStates?): T[]

Defined in: src/manager/entity-manager.ts:1819

Type Parameters ​
T ​

T extends Entity

Parameters ​
entityCtor ​

() => T

entityStates? ​

EntityState | EntityState[]

Returns ​

T[]

Call Signature ​

getEntities<C>(entityCtors, entityStates?): InstanceType<C[number]>[]

Defined in: src/manager/entity-manager.ts:1821

Several types at once: getEntities([Customer, Order]) is (Customer | Order)[].

Type Parameters ​
C ​

C extends () => Entity[]

Parameters ​
entityCtors ​

[...C[]]

entityStates? ​

EntityState | EntityState[]

Returns ​

InstanceType<C[number]>[]

Call Signature ​

getEntities(entityTypeNames?, entityStates?): Entity[]

Defined in: src/manager/entity-manager.ts:1822

Parameters ​
entityTypeNames? ​

string | string[]

entityStates? ​

EntityState | EntityState[]

Returns ​

Entity[]

Call Signature ​

getEntities(entityTypes?, entityStates?): Entity[]

Defined in: src/manager/entity-manager.ts:1823

Parameters ​
entityTypes? ​

EntityType | EntityType[]

entityStates? ​

EntityState | EntityState[]

Returns ​

Entity[]


getEntityByKey() ​

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

Param ​

entityKey

The EntityKey of the Entity to be located.

Param ​

type

The EntityType for this key.

Param ​

typeName

The EntityType name for this key.

Param ​

keyValues

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

Call Signature ​

getEntityByKey<T>(entityCtor, keyValues): T | null

Defined in: src/manager/entity-manager.ts:1551

Returns the entity in this manager's cache with this key, or null if there is none. It does not query the server; see EntityManager.fetchEntityByKey for that. Given the constructor of a class registered with the MetadataStore, the result has that class's type.

ts
// assume em1 is an EntityManager containing a number of preexisting entities,
// and that Employee is registered with its MetadataStore.
const employee = em1.getEntityByKey(Employee, 1);   // Employee | null

A key of more than one property is clearest given by name - see KeyValues:

ts
const detail = em1.getEntityByKey(OrderDetail, { orderID: 10248, productID: 11 });
Type Parameters ​
T ​

T extends Entity

Parameters ​
entityCtor ​

() => T

keyValues ​

any[] | KeyValue | KeyValues<T>

Returns ​

T | null

Call Signature ​

getEntityByKey(entityKey): Entity | null

Defined in: src/manager/entity-manager.ts:1564

Returns the entity in this manager's cache with this key, or null if there is none. It does not query the server; see EntityManager.fetchEntityByKey for that.

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

EntityKey

Returns ​

Entity | null

Call Signature ​

getEntityByKey(typeName, keyValues): Entity | null

Defined in: src/manager/entity-manager.ts:1575

Returns the entity in this manager's cache with this key, or null if there is none. It does not query the server; see EntityManager.fetchEntityByKey for that.

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

string

keyValues ​

any

Returns ​

Entity | null

Call Signature ​

getEntityByKey(type, keyValues): Entity | null

Defined in: src/manager/entity-manager.ts:1587

Returns the entity in this manager's cache with this key, or null if there is none. It does not query the server; see EntityManager.fetchEntityByKey for that.

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
const employeeType = em1.metadataStore.getAsEntityType("Employee");
const employee = em1.getEntityByKey(employeeType, 1);
// employee will either be an entity or null.
Parameters ​
type ​

EntityType

keyValues ​

any

Returns ​

Entity | null


hasChanges() ​

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

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

ts
// 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.

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

or to a collection of EntityTypes, named or given as EntityTypes

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
if (em1.hasChanges(["Customer", "Order"])) {
    // do something interesting
}

Param ​

entityTypes

The EntityType or EntityTypes for which 'changed' entities will be found.

Param ​

entityTypeNames

The EntityType name or names for which 'changed' entities will be found.

Call Signature ​

hasChanges<T>(entityCtor): boolean

Defined in: src/manager/entity-manager.ts:1706

Type Parameters ​
T ​

T extends Entity

Parameters ​
entityCtor ​

() => T

Returns ​

boolean

Call Signature ​

hasChanges(entityCtors): boolean

Defined in: src/manager/entity-manager.ts:1707

Parameters ​
entityCtors ​

() => Entity[]

Returns ​

boolean

Call Signature ​

hasChanges(): boolean

Defined in: src/manager/entity-manager.ts:1708

Returns ​

boolean

Call Signature ​

hasChanges(entityTypeNames): boolean

Defined in: src/manager/entity-manager.ts:1709

Parameters ​
entityTypeNames ​

string | string[]

Returns ​

boolean

Call Signature ​

hasChanges(entityTypes): boolean

Defined in: src/manager/entity-manager.ts:1710

Parameters ​
entityTypes ​

EntityType | EntityType[]

Returns ​

boolean


importEntities() ​

Imports a previously exported result into this EntityManager.

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.

ts
// assume em1 is an EntityManager containing a number of existing entities.
const bundle = em1.exportEntities();
// bundle can be stored in window.localStorage or just held in memory.
const 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.

ts
const 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.

Param ​

exportedString

The result of a previous 'export' call.

Param ​

importConfig

A configuration object.

Param ​

importConfig.mergeStrategy

A MergeStrategy to use when merging into an existing EntityManager.

Param ​

importConfig.metadataVersionFn

A function called with { metadataVersion, metadataStoreName } from the import bundle, for version checking; throw from it to reject the import. Only called when the bundle was exported without its metadata.

Call Signature ​

importEntities(exportedString, config?): ImportResult

Defined in: src/manager/entity-manager.ts:897

Parameters ​
exportedString ​

string

config? ​

ImportConfig

Returns ​

ImportResult

Call Signature ​

importEntities(exportedData, config?): ImportResult

Defined in: src/manager/entity-manager.ts:898

Parameters ​
exportedData ​

Object

config? ​

ImportConfig

Returns ​

ImportResult


rejectChanges() ​

rejectChanges(): Entity[]

Defined in: src/manager/entity-manager.ts:1804

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

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

Returns ​

Entity[]

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


saveChanges() ​

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. Async

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.

ts
// assume em1 is an EntityManager containing a number of preexisting entities.
// This could include added, modified and deleted entities.
// A failed save rejects, so the await throws.
const saveResult = await em1.saveChanges();
const savedEntities = saveResult.entities;
const keyMappings = saveResult.keyMappings;

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

ts
// save only the changed customers
const saveOptions = new SaveOptions({ allowConcurrentSaves: true });
const saveResult = await em1.saveChanges(em1.getChanges(Customer), saveOptions);

The callback and errorCallback arguments are deprecated. They still work, but the promise is the supported form and the callbacks will be removed in a future major version.

Param ​

entities

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.

Param ​

saveOptions

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

Param ​

callback

Deprecated. Function called on success.

Param ​

errorCallback

Deprecated. Function called on failure.

Call Signature ​

saveChanges(entities?, saveOptions?): Promise<SaveResult>

Defined in: src/manager/entity-manager.ts:1299

Parameters ​
entities? ​

Entity[] | null

saveOptions? ​

SaveOptions

Returns ​

Promise<SaveResult>

Call Signature ​

saveChanges(entities, saveOptions, callback?, errorCallback?): Promise<SaveResult>

Defined in: src/manager/entity-manager.ts:1301

Parameters ​
entities ​

Entity[] | null | undefined

saveOptions ​

SaveOptions | undefined

callback? ​

Function

errorCallback? ​

Function

Returns ​

Promise<SaveResult>

Deprecated ​

Await the returned promise instead of passing callbacks.


saveChangesValidateOnClient() ​

saveChangesValidateOnClient(entitiesToSave): Error | null

Defined in: src/manager/entity-manager.ts:1497

Run the "saveChanges" pre-save client validation logic.

This is NOT a general purpose validation method. It is intended for utilities that must know if saveChanges would reject the save due to client validation errors.

It only validates entities if the EntityManager's ValidationOptions.validateOnSave is true.

Parameters ​

entitiesToSave ​

Entity[]

{Array of Entity} The list of entities to save (to validate).

Returns ​

Error | null

Validation error or null if no error


saveChangesValidateOnClientAsync() ​

saveChangesValidateOnClientAsync(entitiesToSave): Promise<Error | null>

Defined in: src/manager/entity-manager.ts:1521

The check EntityManager.saveChangesValidateOnClient makes, with async validators run too: each entity is validated with EntityAspect.validateEntityAsync. saveChanges uses this in its place when any of the entities it saves has an async validator.

Parameters ​

entitiesToSave ​

Entity[]

The entities to validate.

Returns ​

Promise<Error | null>

A promise of the error saveChanges would reject with, or null.


setProperties() ​

setProperties(config): void

Defined in: src/manager/entity-manager.ts:626

General purpose property set method. Any of the properties in the EntityManagerConfig may be set.

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

Parameters ​

config ​

EntityManagerConfig

An object containing the selected properties and values to set.

Returns ​

void


importEntities() ​

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

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

Param ​

exportedString

The result of a previous 'exportEntities' call as a string

Param ​

exportedData

The result of a previous 'exportEntities' call as an Object.

Param ​

config

A configuration object.

Param ​

config.mergeStrategy

A MergeStrategy to use when merging into an existing EntityManager.

Param ​

config.metadataVersionFn

A function called with { metadataVersion, metadataStoreName } from the import bundle, for version checking; throw from it to reject the import. Only called when the bundle was exported without its metadata.

Call Signature ​

static importEntities(exportedString, config?): EntityManager

Defined in: src/manager/entity-manager.ts:733

Parameters ​
exportedString ​

string

config? ​

ImportConfig

Returns ​

EntityManager

Call Signature ​

static importEntities(exportedData, config?): EntityManager

Defined in: src/manager/entity-manager.ts:734

Parameters ​
exportedData ​

Object

config? ​

ImportConfig

Returns ​

EntityManager

Released under the MIT License.