如何取消删除已删除EntityState的实体

时间:2016-08-02 14:05:54

标签: breeze

我有一个具有复合主键的实体,可以模拟多对多的关系:

public class ActualAnswer
{
    [Key]
    [Column(Order = 0)]
    public int AnsweredQuestionID { get; set; }

    [Key]
    [Column(Order = 1)]
    public int AnswerID { get; set; }

}

如果我使用Breeze在客户端应用程序中删除其中一个实体,则其状态将设置为已删除:

function deleteEntity(entity) {
    var ea = entity.entityAspect;
    ea.setDeleted();
}

如果用户改变主意,我目前尝试重新创建实体:

createEntity("ActualAnswer", {
    AnsweredQuestionID: answeredquestionid,
    AnswerID: answerid
});

使用我的Breeze EntityManager调用此函数:

function createEntity(entityType, initialValues) {
    var entity = manager.createEntity(entityType, initialValues)
    return entity;
}

然而,这会导致错误:

  

合并策略'禁止'不允许您附加实体   当已经附加具有相同密钥的实体时:   ActualAnswer:#etc

确实,我们已经拥有一个具有相同密钥的实体 - 但它位于"已删除"状态。

那么,我该如何检索并取消删除呢?

或者,我可以安全地使用不同的合并策略吗?我需要注意哪些陷阱?我是否可以通过仅在此特定实体上使用合并策略来最小化风险?

2 个答案:

答案 0 :(得分:1)

这是我找到从缓存中检索已删除项目并取消删除它们的唯一方法:

//A MergeStrategy of 'Disallowed' does not allow you to attach an entity 
//when an entity with the same key is already attached
//so we need to check for deleted entities and undelete them
var queryOptions = manager.queryOptions.using({
    includeDeleted: true,
    fetchStrategy: breeze.FetchStrategy.FromLocalCache
});

var existing = EntityQuery
    .from('ActualAnswers')
    .where('AnsweredQuestionID', '==', this.ID)
    .where('AnswerID', '==', answerid)
    .using(queryOptions)
    .using(manager)
    .executeLocally();

if (existing.length > 0 && existing[0].entityAspect.entityState.isDeleted()) {
    //rejectChanges fixes navigation properties. setUnchanged doesn't
    existing[0].entityAspect.rejectChanges(); 
}
else {
    createEntity("ActualAnswer", {
        AnsweredQuestionID: this.ID,
        AnswerID: answerid
    });
}

答案 1 :(得分:0)

为什么不直接将状态更改为修改?

function unDeleteEntity(entity) {
    var ea = entity.entityAspect;
    ea.setModified();
}