![](/img/trans.png)
[英]The instance of entity type 'Entity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
[英]The instance of entity type ‘Bus’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked
我的项目中有远征实体。
[Table("Expeditions")]
public class Expedition
{
public int Id { get; set; }
public Bus Bus { get; set; }
[ForeignKey("Bus")]
public int BusId { get; set; }
}
并且 Expedition 实体有一个外键。 来自总线实体的外键。
我使用来自前端的信息创建了一个 EpeditionDTO。想尝试将 ExpeditionDTO 转换为 Expedition 并将它们添加到数据库中。
public void Add(ExpeditionDTO item)
{
try
{
Bus Bus = _mapper.Map<Bus>(item.Bus);
var expedition = new Expedition()
{
Id = item.Id,
Bus = Bus,
BusId = Bus.Id
};
_expeditionRepository.Add(expedition);
_unitOfWork.Save();
}
catch(Exception ex)
{
throw ex;
}
}
我的 Add 方法是这样的:
public virtual void Add(T Entity)
{
_context.Add<T>(Entity);
}
当我尝试这个时,我得到了这个错误。
无法跟踪实体类型“Bus”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。 附加现有实体时,请确保仅附加一个具有给定键值的实体实例。 考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。
我怎么解决这个问题。
你应该只传递BusId
var expedition = new Expedition()
{
Id = item.Id,
BusId = Bus.Id
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.