I have a class named Classroom which is something like:
public class Classroom
{
[Key]
public int ClassroomId { get; set; }
public string ClassroomTitle { get; set; }
public string AccessCode { get; set; }
public string ColorPicker { get; set; }
public LevelGroup LevelGroup { get; set; }
}
The LevelGroup class is something like:
public class LevelGroup
{
public int MLevelId { get; set; }
public int MGroupId { get; set; }
public Level Level { get; set; }
public Group Group { get; set; }
}
In my API, I am trying to retrieve the data of type Classroom like:
[HttpPost("AddClassroom")]
public async Task<JsonResult> AddClassroom([FromBody] Classroom classroom)
{
if (!ModelState.IsValid)
{
return Json(new ApiMessage
{
HasError = true,
Message = "InvalidModel",
});
}
try
{
_context.Add(classroom);
await _context.SaveChangesAsync();
return Json(new ApiMessage
{
HasError = false,
Message = "Success"
});
}
catch (Exception e)
{
return Json(new ApiMessage
{
HasError = true,
Message = e.Message
});
}
}
From the POSTMAN, I tried to hit the API at some url and in the BODY, I've passed this object:
{
"classroomTitle": "SWE",
"accessCode": "6s1x4d1",
"colorPicker": "blue",
"levelGroup": {
"mLevelId": 1,
"mGroupId": 2
}
}
But, This is not working. It says:
An exception occurred in the database while saving changes for context type 'mirror_api.Models.ApplicationDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'UNIQUE constraint failed: LevelGroups.MGroupId, LevelGroups.MLevelId'.
How to solve this problem?