简体   繁体   English

使用Entity Framework更新行时出现异常

[英]Exception when updating rows with Entity Framework

I get the following exception when trying to update my records: 尝试更新记录时出现以下异常:

System.InvalidOperationException: An object with the same key already exists in the ObjectStateManager. System.InvalidOperationException:ObjectStateManager中已存在具有相同键的对象。 The ObjectStateManager cannot track multiple objects with the same key. ObjectStateManager无法使用相同的键跟踪多个对象。

The code is as follows: (player is a contract version of player which is passed to method as parameter, ToDbPlayer() is an extension method that takes a contract.Player object and creates an equivalent one for the DB) 代码如下:(播放器是播放器的合约版本,作为参数传递给方法,ToDbPlayer()是一个扩展方法,它接受contract.Player对象并为DB创建一个等效的对象)

using (var context = _contextFactory.CreateEntities())
{
    var dbPlayer = context.Players.Find(player.PlayerId);
    var entity = context.Players.Attach(player.ToDbPlayer()); //here error occurs
    context.Entry(entity).State = dbPlayer == null ? EntityState.Added : EntityState.Modified;
    context.SaveChanges();
}

I'm confused as to what to do - I'm trying to simply update the records in the DB however its falling over when I try to attach it to the context. 我很困惑该怎么做 - 我只是想简单地更新数据库中的记录,但是当我尝试将它附加到上下文时它会掉下来。

I'm not overly confident on my EF skills so if someone can point me in the right direction, it'd be appreciated. 我对自己的EF技能并不过分自信,所以如果有人能指出我正确的方向,我们将不胜感激。

When you do the find the entity will already be attached, so you will not be able to attach it again. 当您执行查找时,实体将已附加,因此您将无法再次附加它。

If you need to get the entity without it being tacked use .AsNoTracking() ie 如果您需要获取实体而不使用它。使用.AsNoTracking()即

var dbPlayer = context.Players.AsNoTracking().Find(player.PlayerId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM