简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM