【发布时间】:2020-02-24 18:05:43
【问题描述】:
我有一个名为 Classroom 的类,类似于:
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; }
}
LevelGroup 类类似于:
public class LevelGroup
{
public int MLevelId { get; set; }
public int MGroupId { get; set; }
public Level Level { get; set; }
public Group Group { get; set; }
}
在我的 API 中,我试图检索 Classroom 类型的数据,例如:
[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
});
}
}
通过 POSTMAN,我尝试在某个 url 和 BODY 中访问 API,我已经传递了这个对象:
{
"classroomTitle": "SWE",
"accessCode": "6s1x4d1",
"colorPicker": "blue",
"levelGroup": {
"mLevelId": 1,
"mGroupId": 2
}
}
但是,这不起作用。它说:
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'.
如何解决这个问题?
【问题讨论】:
-
错误很明显,
LevelGroups.MGroupId, LevelGroups.MLevelId列具有唯一约束,这意味着它们只能包含唯一且不存在的值。替换行、禁用唯一约束或启用列的自动增量。 -
很可能您已经将此类实体添加到数据库中。您应该更改请求中新值所独有的属性,或者只是将您的方法重新设计为stackoverflow.com/questions/5557829/…
-
@nullptr.t 好吧,我明白你的意思了。但问题是,我不想在 LevelGroups 表中插入新行。我只想在课堂表中添加一个新行。而在课堂上,我只想弄清楚它属于哪个LevelGroup。另外需要注意的是,LevelGroup 类定义了另外两个类 Level 和 Group 的多对多关系。
-
@EugenePodskal 我猜它没有
标签: c# asp.net-core entity-framework-core