Jose Alonso Monge
Jose Alonso Monge

Reputation: 1034

How to add a property to an entity dynamically?

How do you add a property to an entity dynamically? I've been looking, but haven't found anything.

For example, I have this model definition (I'm using the WebSQL provider):

$data.Entity.extend('$db.Types.Person', {
        id: { type: 'int', key: true, computed: true },
        name: { type: 'string' }
    });

$data.EntityContext.extend('$db.Types.DBContext', {
        Persons: { type: $data.EntitySet, elementType: $db.Types.Person},
    });

At some point I need to extend my model with new properties. Initially I don't know these properties' names.

Upvotes: 0

Views: 465

Answers (1)

Robesz
Robesz

Reputation: 1646

The syntax is very simple for this, but the background info is more important, please read the whole answer before you reuse the snippet.

The YourType can be extended with new fields using the YourType.addMember() function. See this example snippet:

$data.Entity.extend('Product', {
  id: { type: 'int', key: true, computed: true },
  Name: { type: 'string' }
});

$data.EntityContext.extend('Northwind', {
  Products: { type: $data.EntitySet, elementType: Product},
});

Product.addMember('Description', {
    type:'string', 
    key: false, 
    computed: false, 
    required: false
});

var context = new Northwind({provider: 'webSql', databaseName: 'Northwind'});

context.onReady(function() {
    var product1 = new Product({ Name: 'Beer', Description: 'tasty'});
    context.Products.add(product1);
    context.saveChanges(function(result) {
        //check the content of WebSQL DB
        console.log(product1);
    });
});

You can user the addMember() only before creating an instance of the context.

Important info: There is no data migration/merge by in the library, and the default behavior on schema modification for webSql is to drop&re-create the DB. As IndexedDB isn't bound to a schema, the existing records won't be dropped. Make a try by running this code and adding more fields, here is a working JSFiddle.

The real solution is to use Schema Evolution module of JayData Pro to manage the changes in your data model.

Upvotes: 1

Related Questions