简体   繁体   English

如何动态地向实体添加属性?

[英]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): 例如,我有以下模型定义(我正在使用WebSQL提供程序):

$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. 可以使用YourType.addMember()函数使用新字段扩展YourType.addMember() 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. 您只能在创建上下文实例之前addMember()

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. 重要信息:库中没有数据迁移/合并,并且对webSql进行架构修改的默认行为是删除并重新创建数据库。 As IndexedDB isn't bound to a schema, the existing records won't be dropped. 由于IndexedDB未绑定到架构,因此不会删除现有记录。 Make a try by running this code and adding more fields, here is a working JSFiddle . 通过运行此代码并添加更多字段来进行尝试,这是一个可用的JSFiddle

The real solution is to use Schema Evolution module of JayData Pro to manage the changes in your data model. 真正的解决方案是使用JayData Pro的 Schema Evolution模块来管理数据模型中的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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