Options
All
  • Public
  • Public/Protected
  • All
Menu

Class EntityManager

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

Hierarchy

  • EntityManager

Index

Constructors

constructor

  • EntityManager constructor.

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

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

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

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

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

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

    or

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

    Parameters

    Returns EntityManager

Events

entityChanged

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

eventargs

-

  • entityAction - The EntityAction that occured.
  • entity - The entity that changed. If this is null, then all entities in the entityManager were affected.
  • args - Additional information about this event. This will differ based on the entityAction.
 let 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.
     let action = changeArgs.entityAction;
     let entity = changeArgs.entity;
     // .. do something to this entity when it is changed.
 });

});

hasChangesChanged

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

eventargs

-

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

validationErrorsChanged

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

eventargs

-

  • 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'
 let 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) {
             let entity == validationChangeArgs.entity;
             let errorsAdded = validationChangeArgs.added;
             let errorsCleared = validationChangeArgs.removed;
             // ... do something interesting with the order.
         });
     });
 });

Properties

dataService

dataService: DataService

The DataService associated with this EntityManager. Read Only

isLoading

isLoading: boolean

isRejectingChanges

isRejectingChanges: boolean

keyGenerator

keyGenerator: KeyGenerator

The KeyGenerator associated with this EntityManager. Read Only

keyGeneratorCtor

keyGeneratorCtor: { constructor: any }

The KeyGenerator constructor associated with this EntityManager. Read Only

Type declaration

metadataStore

metadataStore: MetadataStore

The MetadataStore associated with this EntityManager. Read Only

queryOptions

queryOptions: QueryOptions

The QueryOptions associated with this EntityManager. Read Only

saveOptions

saveOptions: SaveOptions

The SaveOptions associated with this EntityManager. Read Only

serviceName

serviceName: string

The service name associated with this EntityManager. Read Only

validationOptions

validationOptions: ValidationOptions

The ValidationOptions associated with this EntityManager. Read Only

Methods

acceptChanges

  • acceptChanges(): void

addEntity

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

    // assume em1 is an EntityManager containing a number of existing entities.
    let custType = em1.metadataStore.getEntityType("Customer");
    let 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.
    let custType = em1.metadataStore.getEntityType("Customer");
    let cust1 = custType.createEntity();
    em1.attachEntity(cust1, EntityState.Added);
    

    Parameters

    • entity: Entity

      The entity to add.

    Returns Entity

    The added entity.

attachEntity

  • Attaches an entity to this EntityManager with a specified EntityState.

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

    Parameters

    • entity: Entity

      The entity to add.

    • Optional entityState: EntityState

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

    • Optional 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 Entity

    The attached entity.

clear

  • clear(): void
  • 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.

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

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

    // assume em1 is an EntityManager containing a number of existing entities.
    let 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.

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

    Parameters

    • typeName: string

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

    • Optional initialValues: Object

      (default=null) Configuration object of the properties to set immediately after creation.

    • Optional entityState: EntityState

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

    • Optional mergeStrategy: MergeStrategy

      (default = MergeStrategy.Disallowed) - 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.

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

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

    Parameters

    Returns Entity

    A new Entity of the specified type.

detachEntity

  • detachEntity(entity: Entity): any
  • Detaches an entity from this EntityManager.

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

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

    or with callbacks

    let em = new EntityManager(serviceName);
    let query = new EntityQuery("Orders");
    em.executeQuery(query,
        function(data) {
            let 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.

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

    Parameters

    Returns Promise<QueryResult>

    Promise of

    • results - An array of entities
    • retrievedEntities - A array of all of the entities returned by the query. Differs from results (above) when .expand() is used.
    • query - The original EntityQuery or query string
    • entityManager - The EntityManager.
    • httpResponse - The [[IHttpResponse]] returned from the server.
    • inlineCount - 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.
  • Executes the specified query. Async

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

    or with callbacks

    let em = new EntityManager(serviceName);
    let query = new EntityQuery("Orders");
    em.executeQuery(query,
        function(data) {
            let 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.

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

    Parameters

    Returns Promise<QueryResult>

    Promise of

    • results - An array of entities
    • retrievedEntities - A array of all of the entities returned by the query. Differs from results (above) when .expand() is used.
    • query - The original EntityQuery or query string
    • entityManager - The EntityManager.
    • httpResponse - The [[IHttpResponse]] returned from the server.
    • inlineCount - 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.

executeQueryLocally

  • 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

    let em = new EntityManager(serviceName);
    let query = new EntityQuery("Orders");
    let 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

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

    Parameters

    Returns any[]

    Array of entities from cache that satisfy the query

exportEntities

  • exportEntities(entities?: Entity[] | EntityType[] | string[], exportConfig?: { asString?: boolean; includeMetadata?: boolean } | boolean): string | Object
  • 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.

     // let em1 be an EntityManager containing a number of existing entities.
    // export every entity in em1.
    let bundle = em1.exportEntities();
    // save to the browser's local storage
    window.localStorage.setItem("myEntityManager", bundle);
    // later retrieve the export
    let bundleFromStorage = window.localStorage.getItem("myEntityManager");
    // import the retrieved export bundle into another manager
    let 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.

    // get em1's unsaved changes (an array) and export them.
    let changes = em1.getChanges();
    let 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.

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

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

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

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

    // Export all Customer and Employee entities (and also exclude metadata)
    let 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.

    // Export all Customer and Employee entities as JSON and exclude the metadata
    let 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);
    

    Parameters

    • Optional entities: Entity[] | EntityType[] | string[]

      The entities to export or the EntityType(s) of the entities to export; all entities are exported if this parameter is omitted or null.

    • Optional exportConfig: { asString?: boolean; includeMetadata?: boolean } | boolean

      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.

    Returns string | Object

    The export bundle either serialized as a string (default) or as a JSON object. The bundle contains the metadata (unless excluded) and the entity data grouped by type. The entity data include property values, change-state, and temporary key mappings (if any).

    The export bundle internals are deliberately undocumented. This Breeze-internal representation of entity data is suitable for export, storage, and import. The schema and contents of the bundle may change in future versions of Breeze. Manipulate it at your own risk with appropriate caution.

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.

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

    Parameters

    • typeName: string

      The EntityType name for this key.

    • keyValues: any | any[]

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

    • Optional checkLocalCacheFirst: boolean

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

    Returns Promise<IEntityByKeyResult>

    • Properties on the promise success result
    • entity {Object} The entity returned or null
    • entityKey {EntityKey} The entityKey of the entity to fetch.
    • fromCache {Boolean} Whether this entity was fetched from the server or was found in the local cache.
  • 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.

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

    Parameters

    • entityType: EntityType
    • keyValues: any | any[]
    • Optional checkLocalCacheFirst: boolean

    Returns Promise<IEntityByKeyResult>

    • Properties on the promise success result
    • entity {Object} The entity returned or null
    • entityKey {EntityKey} The entityKey of the entity to fetch.
    • fromCache {Boolean} Whether this entity was fetched from the server or was found in the local cache.
  • 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.

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

    Parameters

    • entityKey: EntityKey
    • Optional checkLocalCacheFirst: boolean

    Returns Promise<IEntityByKeyResult>

    • Properties on the promise success result
    • entity {Object} The entity returned or null
    • entityKey {EntityKey} The entityKey of the entity to fetch.
    • fromCache {Boolean} Whether this entity was fetched from the server or was found in the local cache.

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.

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

    Parameters

    Returns Promise<any>

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

findEntityByKey

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

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

    Use getEntityByKey instead

    Parameters

    Returns Entity

    An Entity or null;

generateTempKeyValue

  • generateTempKeyValue(entity: Entity): any
  • 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.

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let custType = em1.metadataStore.getEntityType("Customer");
     let customer = custType.createEntity();
     let customerId = em.generateTempKeyValue(customer);
     // 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) {
         let 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.
     })
    

    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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let changedCustomers = em1.getChanges(custType);
    

    or to a collection of EntityTypes

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

    Returns Entity[]

    An array of Entities

  • 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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let changedCustomers = em1.getChanges(custType);
    

    or to a collection of EntityTypes

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

    Parameters

    • entityTypeNames: string | string[]

    Returns Entity[]

    An array of Entities

  • 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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let changedCustomers = em1.getChanges(custType);
    

    or to a collection of EntityTypes

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

    Parameters

    Returns Entity[]

    An array of Entities

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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let customers = em1.getEntities(custType);
    

    or to a collection of EntityTypes

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     let addedCustomersAndOrders = em1.getEntities([custType, orderType], EntityState.Added);
    

    Parameters

    • Optional entityTypeNames: string | string[]
    • Optional entityStates: EntityState | EntityState[]

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

    Returns Entity[]

    An array of Entities

  • 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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let customers = em1.getEntities(custType);
    

    or to a collection of EntityTypes

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     let addedCustomersAndOrders = em1.getEntities([custType, orderType], EntityState.Added);
    

    Parameters

    Returns Entity[]

    An array of Entities

getEntityByKey

  • getEntityByKey(entityKey: EntityKey): Entity | null
  • getEntityByKey(typeName: string, keyValues: any | any[]): Entity | null
  • getEntityByKey(type: EntityType, keyValues: any | any[]): Entity | null
  •  // assume em1 is an EntityManager containing a number of preexisting entities.
     let employeeType = em1.metadataStore.getEntityType("Employee");
     let employeeKey = new EntityKey(employeeType, 1);
     let employee = em1.getEntityByKey(employeeKey);
     // employee will either be an entity or null.
    

    Parameters

    Returns Entity | null

    An Entity or null;

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

    Parameters

    • typeName: string
    • keyValues: any | any[]

    Returns Entity | null

    An Entity or null;

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

    Parameters

    Returns Entity | null

    An Entity or null;

hasChanges

  • hasChanges(): boolean
  • hasChanges(entityTypeNames: string | string[]): boolean
  • hasChanges(entityTypes: EntityType | EntityType[]): 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.

    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.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     if ( em1.hasChanges( [custType, orderType]) {
         // do something interesting
     }
    

    Returns boolean

    Whether there are any changed entities that match the types specified..

  • 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

     // 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.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     if ( em1.hasChanges( [custType, orderType]) {
         // do something interesting
     }
    

    Parameters

    • entityTypeNames: string | string[]

    Returns boolean

    Whether there are any changed entities that match the types specified..

  • 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

     // 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.
     let 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.
     let custType = em1.metadataStore.getEntityType("Customer");
     let orderType = em1.metadataStore.getEntityType("Order");
     if ( em1.hasChanges( [custType, orderType]) {
         // do something interesting
     }
    

    Parameters

    Returns boolean

    Whether there are any changed entities that match the types specified..

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.

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

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

    Parameters

    • exportedString: string

      The result of a previous 'export' call.

    • Optional config: ImportConfig

    Returns ImportResult

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

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

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

    Parameters

    Returns ImportResult

    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.

rejectChanges

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

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

    Returns Entity[]

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

saveChanges

  • saveChanges(entities?: Entity[] | null, saveOptions?: SaveOptions, callback?: Function, errorCallback?: Function): Promise<SaveResult>
  • 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.

     // assume em1 is an EntityManager containing a number of preexisting entities.
     // This could include added, modified and deleted entities.
     em.saveChanges().then(function(saveResult) {
         let savedEntities = saveResult.entities;
         let keyMappings = saveResult.keyMappings;
     }).catch(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.
     let saveOptions = new SaveOptions({ allowConcurrentSaves: true });
     em.saveChanges(entitiesToSave, saveOptions).then(function(saveResult) {
         let savedEntities = saveResult.entities;
         let keyMappings = saveResult.keyMappings;
     }).catch(function (e) {
         // e is any exception that was thrown.
     });
    

    Callback methods can also be used

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

    Parameters

    • Optional entities: Entity[] | null

      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.

    • Optional saveOptions: SaveOptions

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

    • Optional callback: Function

      Function called on success.

    • Optional errorCallback: Function

      Function called on failure.

    Returns Promise<SaveResult>

    Promise

saveChangesValidateOnClient

  • saveChangesValidateOnClient(entitiesToSave: Entity[]): Error
  • 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[]

      The list of entities to save (to validate).

    Returns Error

    Validation error or null if no error

setProperties

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

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

    Parameters

    Returns void

Static importEntities

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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let bundleFromStorage = window.localStorage.getItem("myEntityManager");
     // and imported
     let em2 = EntityManager.importEntities(bundleFromStorage);
     // em2 will now have a complete copy of what was in em1
    

    Parameters

    • exportedString: string

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

    • Optional config: ImportConfig

      A configuration object.

    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.

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

     // assume em1 is an EntityManager containing a number of preexisting entities.
     let 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.
     let bundleFromStorage = window.localStorage.getItem("myEntityManager");
     // and imported
     let em2 = EntityManager.importEntities(bundleFromStorage);
     // em2 will now have a complete copy of what was in em1
    

    Parameters

    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.

Object literals

helper

helper: object

unwrapChangedValues

unwrapChangedValues: unwrapChangedValues = unwrapChangedValues

unwrapInstance

unwrapInstance: unwrapInstance = unwrapInstance

unwrapOriginalValues

unwrapOriginalValues: unwrapOriginalValues = unwrapOriginalValues

Generated using TypeDoc