Update mapped entity

by JayData

HTML

<script src="http://include.jaydata.org/datajs-1.0.3-patched.js"></script>
<script src="http://include.jaydata.org/jaydata.js"></script>

JavaScript

var url = 'https://open.jaystack.net/93e8728b-33c9-406e-bf44-43eccdc007b1/17e3bccb-9ffe-493f-aefc-18e10bf25571/api/mydatabase/';

//This example show how to use JayData to query a subset of the fields of an entity over OData and update the results
$data.service(url, function(cf, ct) {
    var db = cf();
    //We wait for the context creation
    db.onReady(function() {
        //We make a projection by defining the properties we need - creates $select in the OData query
        db.Products.map(function ( a ) { 
            return { 
                id: a.id, Name: a.Name, Category: a.Category 
            };
            //the 3rd parameter of the map definies the type of the returned entity
            //without this we get a POCO object, 'default' detect the entity type we query
            //this can be set explicitly by changing 'default' to db.Products.entityType
        }, null, 'default').toArray(function (mappedProduct) { 
            //Let's say we want to update only the first entity
            var product = mappedProduct[0];
            //Attaching the entity is necessary to track changes - BEFORE modifying the properties
            db.Products.attach(product);
            //Objects references using navigation properties should be attached, too
            db.Categories.attach(product.Category);
            //change a property of the object
            product.Name += '1';
            //Save the entity back using OData
            db.saveChanges().then(function() {
                db.Products.toArray($data.debug);
            });
        });
     });
});