RobVious
RobVious

Reputation: 12915

How do I set a property on a breeze entity client-side?

I've tried drilling down into the object and looking at the docs but haven't found anything. I've created an entity and I need to assign some properties manually. I see _backingStore and entityAspect on the object... and I know the property names but don't know how to set them via the breeze entity.

In case it matters, I'm creating a new object and then copying properties over from another object to facilitate cloning.

function createDocument() {
    var manager = datacontext.manager;
    var ds = datacontext.serviceName;
    if (!manager.metadataStore.hasMetadataFor(ds)) {
        manager.fetchMetadata(ds).then(function () {
            return manager.createEntity("Document");
        })
    }
    else {
        return manager.createEntity("Document");
    }
}

function cloneDocument(doc) {
    var clonedDocument = createDocument();

    // Copy Properties Here - how?

    saveChanges()
        .fail(cloneFailed)
        .fin(cloneSucceeded);
 }

Upvotes: 0

Views: 159

Answers (2)

Ward
Ward

Reputation: 17863

And here's another way that works regardless of model library (Angular or KO)

function cloneDocument(doc) {

    var manager = doc.entityAspect.entityManager; // get it from the source

    // Check this out! I'm using an object initializer!
    var clonedDocument = manager.createEntity("Document", {
        description: doc.description,
        foo: doc.foo,
        bar: doc.bar,
        baz: doc.baz
    });

    return clonedDocument;
}

But beware of this:

clonedDocument.docId = doc.docId; // Probably won't work!

Two entities of the same type in the same manager cannot have the same key.

Extra credit: write a utility that copies the properties of one entity to another without copying entityAspect or the key (the id) and optionally clones the entities of a dependent navigation (e.g., the order line items of an order).

Upvotes: 2

PW Kad
PW Kad

Reputation: 14995

Not knowing what your properties might be, here are two scenarios -

function cloneDocument(doc) {
    var clonedDocument = createDocument();

    clonedDocument.docId(doc.docId());
    clonedDocument.description(doc.description());

    saveChanges()
        .fail(cloneFailed)
        .fin(cloneSucceeded);
}

There are a few things to note here - I am assuming you are using Knockout and needing to set the properties. If you are not using Knockout then you can remove the parans and use equals -

    clonedDocument.docId = doc.docId;

I believe this is true for if you are not using Knockout (vanilla js) and if you are using Angular, but I have not used Breeze with Angular yet so bear with me.

Upvotes: 2

Related Questions