Breeze.js - 在保存实体之前更改服务器上实体的属性值

时间:2013-03-27 14:50:20

标签: javascript breeze

我的问题是:

在Breeze.js中,是否有可能在保存此实体之前更改/设置服务器上实体的属性值?

例如,假设存在一个名为产品的实体,并且此实体具有名为价格的属性,我希望在服务器中并在保存实体之前,乘以价格值的常数。

查看herehere,我尝试使用以下方法:BeforeSaveEntity(entityInfo)BeforeSaveEntities(saveMap)SaveChangesCore(saveMap)

source code中,我了解BeforeSaveEntity(entityInfo)BeforeSaveEntities(saveMap)仅用于验证实体。这不是我想要的。

在方法SaveChangesCore(saveMap)中,源代码描述为here,我认为这里是更改实体属性值的地方。

所以我尝试了以下内容,但它没有用。该值未在数据库中更新

protected override List<KeyMapping> SaveChangesCore(Dictionary<Type, List<EntityInfo>> saveMap)
        {
            foreach (var entity in saveMap[typeof(Product)])
            {
                var product = (Product)entity.Entity;

                product.Price =  product.Price * 10; // changing the value of the property    

            }

            return base.SaveChangesCore(saveMap);    
        }

提前致谢,

Bernardo Pacheco

2 个答案:

答案 0 :(得分:3)

您可以在dbcontext类中执行此操作。 您可以覆盖SaveChanges方法并执行以下操作:

public override int SaveChanges() {
    foreach ( var entry in this.ChangeTracker.Entries()
            .Where( e => e.State ==EntityState.Added ) ){
        var entity=entry.Entity as Product;
        if(entity!=null){
            entity.Price =  entity.Price * 10;
        }
    }
    return base.SaveChanges();
}

我假设您正在使用实体框架。

我认为这篇文章也是关于你的问题:

Breeze BeforeSaveEntityonly only allows update to Added entities

答案 1 :(得分:2)

我们有类似的测试正是这样做所以我不确定发生了什么,但我确实有一些建议。第一次改变

foreach (var entity in saveMap[typeof(Product)]) {
   ... 
}

List<EntityInfo> entities;
if (saveMap.TryGetValue(typeof(Product), out entities)) {
   foreach (var entity in entities) { 
      ...
   }
}

原因是saveMap是一个.NET字典,如果找不到密钥,它会在使用索引器(saveMap [typeof(Product)])时抛出KeyNotFoundException。当saveMap不包含特定的entityType时,会有很多情况。

此外,这可能只是一个拼写错误,但重写方法的返回类型应该是Dictionary&lt;类型,列表&lt; EntityInfo&GT;&GT;而不是列表&lt; EntityInfo&GT;

我也会介入你的代码并确保它以你期望的方式执行。您的代码可能会抛出异常,并且在传播到您的UI之前就会被吃掉。