在单个事务中将记录插入到父子表中,但是当发送多个对象时,给出错误实例!无法跟踪实例



我得到了这个异常:

实体类型'CameraActivity'的实例不能被跟踪,因为另一个具有相同键值的{'ActivityId', 'FeatureId', 'CamId'}的实例已经被跟踪了。

在附加现有实体时,确保只附加一个具有给定键值的实体实例。

考虑使用'DbContextOptionsBuilder。EnableSensitiveDataLogging'以查看冲突的键值。"}

这是我的Post方法
public async Task<ActionResult<Camera>> PostCamera(Camera camera)
{
var cameraRecodExists = _context.Cameras.FirstOrDefault(C => C.IPAdress == camera.IPAdress) ;
if (cameraRecodExists !=null)
{
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "Record Already Exists" });
}
else
{
_context.Cameras.Add(camera);
// _context.SaveChanges();
foreach (var activity in camera.CameraActivities)
{
activity.CamId = camera.CamId;
activity.ActivityId = camera.CameraActivities.First().ActivityId;
activity.FeatureId = camera.CameraActivities.First().FeatureId;
}
_context.CameraActivities.AddRange(camera.CameraActivities);
try 
{
await _context.SaveChangesAsync();
}
catch(Exception ex)
{
var a = ex;
}
return CreatedAtAction("GetCamera", new { id = camera.CamId }, camera);
}
}

您可以参考官方文档并尝试保存cameracamera.CameraActivities:

public async Task<ActionResult<Camera>> PostCamera(Camera camera)
{
var cameraRecodExists = _context.Cameras.FirstOrDefault(C => C.IPAdress == camera.IPAdress) ;
if (cameraRecodExists !=null)
{
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "Record Already Exists" });
}
else
{
_context.Cameras.Add(camera); 
try 
{
await _context.SaveChangesAsync();
}
catch(Exception ex)
{
var a = ex;
}
return CreatedAtAction("GetCamera", new { id = camera.CamId }, camera);
}
}

相关内容

  • 没有找到相关文章