【发布时间】:2019-06-10 08:29:26
【问题描述】:
这个问题很常见,但我还是不明白如何正确更新相关实体?
我有以下代码:
public async Task<bool> UpdateStepAssignedToLevelAsync(Step step, Guid levelId, int priority = -1)
{
var item = await this._context.StepLevels
.Include(sl => sl.Step)
.FirstOrDefaultAsync(x => x.StepId == step.Id && x.LevelId == levelId);
if (item == null)
{
return false;
}
//this._context.Entry(item).State = EntityState.Detached;
if (priority > -1)
{
item.Priority = priority;
}
item.Step = step;
//this._context.StepLevels.Update(item);
var rows = await this._context.SaveChangesAsync();
return rows > 0;
}
运行时出现以下错误:
InvalidOperationException: The instance of entity type 'Step' cannot be tracked because another instance with the key value '{Id: 35290c18-5b0a-46a5-8f59-8888cf548df5}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
据我了解,自方法开始时的选择请求以来,该实体正在被跟踪。好的,但是当我分离实体并调用 Update 方法时(参见注释行), Step 实体没有被更改。但 StepLevel 确实如此:优先级正在改变。当我尝试仅调用 Update 时,EF 会尝试插入新步骤而不是更新现有步骤。
那么,你能告诉我,这里最好的做法是什么?
提前非常感谢!
【问题讨论】:
-
您想要 (1) 更新
Step实体或 (2) 仅更新StepLevel的Step导航属性?虽然(2)在您使用StepId == step.Id检索StepLevel时没有意义。 -
我想同时更新 Step(一些字段,例如 Name)和 StepLevel(优先级)实体。
标签: c# sql-update entity-framework-core one-to-many