【发布时间】:2014-08-30 23:18:04
【问题描述】:
我在尝试更新我的 Player 对象时遇到以下异常。
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
我正在抓取实体,将其自动映射到 DTO,在表单中对其进行编辑,将其发送回并在保存之前转换回 EF 对象。
public class Player
{
[Key]
public int PlayerId {get; set;}
//visual only, not a foreign key
public int PlayerCompetitionId {get;set;}
public string FirstName {get; set;}
public string LastName {get; set;}
[Column("ClubId")]
public int? CurrentClubId { get; set; }
[ForeignKey("CurrentClubId")]
public virtual Club CurrentClub { get; set; }
}
public class PlayerDTO
{
public int PlayerId {get; set;}
public virtual int PlayerCompetitionId {get;set;}
public virtual string FirstName {get; set;}
public virtual string LastName {get; set;}
public virtual Club CurrentClub { get; set; }
}
public class Club
{
public int ClubId {get; set;}
public string Name {get; set;}
}
这是我的 AutoMapper 映射:-
AutoMapper.Mapper.CreateMap<Player, PlayerDTO>();
AutoMapper.Mapper.CreateMap<PlayerDTO, Player>()
.ForMember(x => x.CurrentClubId, opt => opt.MapFrom(dto => (dto.CurrentClub.ClubId == 0) ? null : dto.CurrentClub.ClubId as int?))
.ForMember(x => x.CurrentClub, opt => opt.Ignore());
当我保存 DTO 对象时,我可以看到映射看起来很好。 但是当我将 EntityState 设置为 modified 时,我得到了上述异常。
这是我的最终映射代码并保存。
public void SetModified(DTOPlayer updatedPlayer)
{
Player player = AutoMapper.Mapper.Map<Player>(updatedPlayer);
this.Entry(player).State = EntityState.Modified;
}
我的可为空的 int 属性有问题吗? 因为我有另一个 DTO 模型,当我做完全相同的事情时,它可以正确保存。
谢谢。
【问题讨论】:
-
你能显示 this.Entry(player).State = EntityState.Modified;方法?
-
即public DbEntityEntry Entry(object entity);来自实体框架。它在 DbContext 中。应该更明确地使用“base”而不是“this”。
标签: c# entity-framework automapper