C# .NET API:从邮递员发布对象时出现问题

C# .NET API:从邮递员发布对象时出现问题,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我有一个名为教室的班级,类似于: public class Classroom { [Key] public int ClassroomId { get; set; } public string ClassroomTitle { get; set; } public string AccessCode { get; set; } public string ColorPicker { get;

我有一个名为教室的班级,类似于:

    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; }
    }
public class LevelGroup
    {
        public int MLevelId { get; set; }

        public int MGroupId { get; set; }

        public Level Level { get; set; }

        public Group Group { get; set; }
    }
LevelGroup类类似于:

    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; }
    }
public class LevelGroup
    {
        public int MLevelId { get; set; }

        public int MGroupId { get; set; }

        public Level Level { get; set; }

        public Group Group { get; set; }
    }
在我的API中,我试图检索教室类型的数据,如:

 [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
            });
        }
 }
但是,这是行不通的。它说:

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'.

如何解决此问题?

根据您的评论,我知道您希望保存传递的对象,但不希望保存其内部属性,因为它违反了某些DB约束

我要尝试的是在保存之前将这些属性从EF跟踪中分离出来,这样它就不会将
教室.LevelGroup
标记为
添加的
。你可以看到一个例子。您还可以通过为添加到EF上下文()中的每个属性设置适当的状态来控制EF跟踪更改的对象

你还想阅读一本几乎描述了你所追求的东西的书:

var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" };

using (var context = new BloggingContext())
{
    context.Blogs.Attach(existingBlog);
    context.Entry(existingBlog).State = EntityState.Unchanged;

    // Do some more work...  

    context.SaveChanges();
}
但您不希望附加对象,而是希望添加它,然后将其属性之一设置为
EntityState.Distached
以完全忽略它(或
EntityState.Unchanged
以保持跟踪它,但告诉EF此处没有要保存的内容)。更像这样:

...
_context.Add(classroom);
_context.Entry(classroom.LevelGroup).State = EntityState.Detached;
await _context.SaveChangesAsync();
...

当您创建对象时,EF“gegins跟踪给定实体和任何其他可访问实体”,您可以“使用设置单个实体的状态”,如图所示。

错误非常明显,列
LevelGroups.MGroupId,LevelGroups.MLevelId
具有唯一的约束,这意味着它们只能包含唯一且不存在的值。替换行、禁用唯一约束或对列启用自动递增。很可能您已经将此类实体添加到数据库中。您应该更改请求中新值所特有的属性,或者只是将您的方法重新修改为类似这样的内容。这是否回答了您的问题@嗯,我明白你的意思了。但问题是,我不想在LevelGroups表中插入新行。我只想在教室表格中添加一个新行。在教室里,我只想知道它属于哪个级别组。另外需要注意的是,LevelGroup类定义了另外两个类Level和Group的多对多关系。@EugenePodskal我想不是这样的