1

我有以下更新功能

public void UpdateBatchDefinition(BatchDefinition batchToUpdate)
{
    if (batchToUpdate == null)
    {
        throw new ArgumentNullException("batchToUpdate");
    }

    BatchDefinition foundDefinition =
            this.context.BatchDefinitions.SingleOrDefault(definition => definition.Id == batchToUpdate.Id);

    if (foundDefinition != null)
    {
        if (!string.IsNullOrWhiteSpace(batchToUpdate.Name))
        {
            foundDefinition.Name = batchToUpdate.Name;
        }

        if (!string.IsNullOrWhiteSpace(batchToUpdate.Description))
        {
            foundDefinition.Description = batchToUpdate.Description;
        }
        if (!string.IsNullOrWhiteSpace(batchToUpdate.LoadType))
        {
            foundDefinition.LoadType = batchToUpdate.LoadType;
        }

        if (batchToUpdate.JobId != Guid.Empty)
        {
            foundDefinition.JobId = batchToUpdate.JobId;
        }

        foundDefinition.Tables = batchToUpdate.Tables;
        this.context.SaveChanges();
    }
}

我遇到的问题是当我尝试更新表格列表时。表是表的列表,表是另一个表的实体

可以添加、删除或保留表格。我需要用传入的内容更新它

当我现在运行它时,我收到一个“EntityValidationErrors”错误,尽管它不会告诉我验证问题实际上是什么。

在插入时我遇到了同样的错误,但能够使用以下方法修复它

var underlyingContext = this.context as DbContext;
if (underlyingContext != null)
{
    foreach (var table in batchDefinition.Tables)
    {
        // Need to mark the table entity as unchanged or 
        // else EF will treat it as a new table
        underlyingContext.Entry(table).State = EntityState.Unchanged;
    }
}

所以我尝试在这个更新功能中使用它

var underlyingContext = this.context as DbContext;
if (underlyingContext != null)
{
    foreach (var table in foundDefinition.Tables)
    {
        // Need to mark the table entity as unchanged or 
        //else EF will treat it as a new table
        underlyingContext.Entry(table).State = EntityState.Unchanged;
    }
}

foundDefinition.Tables = batchToUpdate.Tables;

而我收到以下错误:

AcceptChanges 无法继续,因为对象的键值与 ObjectStateManager 中的另一个对象冲突。在调用 AcceptChanges 之前确保键值是唯一的。

有什么想法我在这里想念的吗?

4

1 回答 1

0

像这样更改更新方法的结尾:

foreach (var t in foundDefinition.Tables.ToList())
    Context.Tables.Remove(t);

foundDefinition.Tables = batchToUpdate.Tables;
this.context.SaveChanges();

关于您的最后一个错误,据说您的上下文中有一些重复项。因此,EF 无法将上下文更改保存到数据库中(因为上下文中有重复项!)

事实上,我不知道最后一个错误来自添加或删除 - 你没有明确提及。所以,我不知道最后两个代码示例来自你的 add 方法,或者你的 update 方法......

但是对于更新,我在这里提到的技巧必须解决您的更新问题......

于 2013-08-08T08:49:32.783 回答