posting/creating 带有 web api 的子实体对象时如何设置父实体 ID

How to set parent entity Id when posting/creating child entity object with web api

我有两个 Entity-Framework 实体(一个子“Note”,属于一个文件夹)和脚手架网络 api 每个。我可以创建文件夹并希望能够向这些文件夹添加注释。

public class Note
    {
        public int Id {get; set; }
        [MaxLength(50), Required]
        public string NoteTitle { get; set; }
        [MaxLength(1000), Required]
        public string NoteContent { get; set; }
        
        public NoteFolder NoteFolder { get; set; }
    }
    public class NoteFolder
    {
        public int Id { get; set; }
        public string FolderName { get; set; }

    }

我的POST:

let Note = {
                "NoteTitle": this.NoteTitle(),
                "NoteContent": this.NoteContent(),
                "NoteFolder_Id:": ParentFolderId 
                };

            
            $.ajax({
                url: `http://localhost:52657/api/Notes`,
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    window.location.replace("http://localhost:52657/");
                    alert(`Successfully Created New Note: ${Note.NoteTitle}`)
                },
                data: JSON.stringify(Note)
            });

端点:

 // POST: api/Notes
        [ResponseType(typeof(Note))]
        public IHttpActionResult PostNote(Note note)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Notes.Add(note);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = note.Id }, note);
        }

每当我发出 post 请求时,都会创建注释,但外键行 NoteFolder_Id 在我的数据库中为空。如何解决这个问题?

编辑:我试过 posting:

"NoteFolder": { "Id": ParentFolderId }

以便它可以正确序列化,但是这会导致在数据库中创建一个新的文件夹,该文件夹具有自动递增的 Id,并且创建的注释引用了它。

更改注释 class 并执行迁移,

 public class Note
    {
        public int Id {get; set; }
        [MaxLength(50), Required]
        public string NoteTitle { get; set; }
        [MaxLength(1000), Required]
        public string NoteContent { get; set; }

        public int? FolderId { get; set; }

        [ForeignKey("FolderId")]
        public NoteFolder NoteFolder { get; set; }
    }

然后发送 post 格式:

let Note = {
                "NoteTitle": this.NoteTitle(),
                "NoteContent": this.NoteContent(),
                "FolderId": ParentFolderId 
                };

已解决问题。

仍然不确定为什么传递 NoteFolder 对象会导致在数据库中创建一个新文件夹。 https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx本站使用我的初始模型样式来映射1:n。