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

How to undelete an entity with EntityState deleted

我有一个具有复合主键的实体,该主键对多对多关系进行建模:

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;
}

但是,这会导致错误:

A MergeStrategy of 'Disallowed' does not allow you to attach an entity when an entity with the same key is already attached: ActualAnswer:#etc

没错,我们已经有了一个具有相同密钥的实体 - 但它处于 "Deleted" 状态。

那么,我怎样才能检索并取消删除它?

或者,我可以安全地使用不同的合并策略吗?我需要注意哪些陷阱?我可以通过仅对该特定实体使用合并策略来最大限度地降低风险吗?

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

//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
    });
}

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

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