Qvatra
Qvatra

Reputation: 3857

adding entity from one manager to another in breeze

I've created 2 entity managers using the same metadata and want to add some entity from manager1 to manager2.

I'm getting an Error: Cannot attach this entity because the EntityType and MetadataStore associated with this entity does not match this EntityManager's MetadataStore.

here the function that creates managers:

function createLocalManager(servName) {
    var dataService = new breeze.DataService({
        serviceName: servName,
        hasServerMetadata: false
    });

    var metadataStore = new breeze.MetadataStore(); 
    metadataStore.importMetadata(app.metadata); // initialize it from the application's metadata variable

    return new breeze.EntityManager({
        dataService: dataService,
        metadataStore: metadataStore
    });
}

here I get my error:

em1 = createLocalManager('serviceName1');
em1.createEntity("Picture");

em2 = createLocalManager('serviceName2');
em2.addEntity(em1.getEntities()[0]);

Also I've checked and this

em1.metadataStore == em2.metadataStore

return false!!! Why?

Any help would be appreciated!

Upvotes: 1

Views: 255

Answers (1)

DenisK
DenisK

Reputation: 514

Firstly, Breeze provides a method called entityManager.createEmptyCopy() to create a copy of the original EntityManager with the same metadata.

var em2 = em1.createEmptyCopy();

Secondly, since you're using a different DataService, you have to set em2 dataService manually.

var ds = new breeze.DataService({
   serviceName: 'serviceName2',
   hasServerMetadata: false
});

em2.setProperties({dataService: ds});

Finally, the correct way to share entities among multiple entityManagers is to use entityManager.exportEntities and entityManager.importEntities

var picture = em1.createEntity("Picture");
var entitiesToExport = [picture];
var exportedEntities = em1.exportEntities(entitiesToExport);
em2.importEntities(exportedEntities);

This topic of creating multiple managers and sharing data among them is also documented in detail on http://www.breezejs.com/documentation/multiple-managers

Hope this helps.

Upvotes: 2

Related Questions