我得到了这个异常:
这是我的Post方法实体类型'CameraActivity'的实例不能被跟踪,因为另一个具有相同键值的{'ActivityId', 'FeatureId', 'CamId'}的实例已经被跟踪了。
在附加现有实体时,确保只附加一个具有给定键值的实体实例。
考虑使用'DbContextOptionsBuilder。EnableSensitiveDataLogging'以查看冲突的键值。"}
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);
}
}
您可以参考官方文档并尝试保存camera
和camera.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);
}
}