首页 > 解决方案 > EF Core 不会按顺序创建子实体

问题描述

我使用 JSON 字符串来创建实体。

服务器转换 json 字符串,然后将它们添加到上下文中。

调用 Context.SaveChanges() 后,数据被正确保存。

但在那之后,儿童序列被混淆了。

我不知道为什么它们没有按顺序保存。

[楷模]

  public class Parent
  {
     public int Id { get; set; }
     public string Name { get; set; }
     public ICollection<Child> Children { get; set; }
     [ForeignKey("ImageFileId")] // This model is used for storing image files.
     public ImageFile ImageFile { get; set; } 
     public int ImageFileId { get; set; }
  }

  public class Child
  {
     public int Id { get; set; }
     public string Name { get; set; }
     [ForeignKey("ParentId")]
     public Parent Parent { get; set; }
     public int ParentId { get; set; }
  }

[控制器]

  [ApiController]
  [Route("api")]
  public class ApiController : Controller
  {
    [HttpPost]
    public async Task<IActionResult> Create([FromForm] CreateDTO param)
    {
      if (!ModelState.IsValid)
      {
        return BadRequest(ModelState);
      }

      var options = new JsonSerializerOptions
      {
          PropertyNameCaseInsensitive = true
      };

      var entity = JsonSerializer.Deserialize<Parent>(param.Parent, options);

      // The Parent object has children sequentially here.

      _context.Parents.Add(entity);
      await _context.SaveChangesAsync(); // After this, Data aren't saved sequentially in the database.

      // ...
    }
  }

  // ...

  public class CreateDTO
  {
     public string Parent { get; set; }
     public IFormFile[] Files { get; set; }
  }

[发布数据]

{
  parent: {
    name: "Parent Name",
    children: [
      {
        name: "Child 1"
      },
      {
        name: "Child 2"
      },
      {
        name: "Child 3"
      },
      {
        name: "Child 4"
      },
      {
        name: "Child 5"
      },
      {
        name: "Child 6"
      },
      {
        name: "Child 7"
      },
      {
        name: "Child 8"
      }
    ]
  }
}

[保存的数据](在数据库中没有保存为json数据,我这里只是用json表示)

{
  Parent: {
    Id: 1,
    Name: "Parent Name",
    ImageFileId: 1,
    Children: [
      {
        Id: 1,
        Name: "Child 1",
        ParentId: 1,
      },
      {
        Id: 2,
        Name: "Child 4",
        ParentId: 1,
      },
      {
        Id: 3,
        Name: "Child 3",
        ParentId: 1,
      },
      {
        Id: 4,
        Name: "Child 8",
        ParentId: 1,
      },
      {
        Id: 5,
        Name: "Child 5",
        ParentId: 1,
      },
      {
        Id: 6,
        Name: "Child 2",
        ParentId: 1,
      },
      {
        Id: 7,
        Name: "Child 7",
        ParentId: 1,
      },
      {
        Id: 8,
        Name: "Child 6",
        ParentId: 1,
      }
    ]
  }
}

标签: asp.net-coreentity-framework-core

解决方案


恕我直言,保持顺序的最佳方法是将 OrderNum 字段添加到 Children

但如果你想使用 id 值保存相同的子序列,试试这个

 var entity = JsonSerializer.Deserialize<Parent>(param.Parent, options);
 var children=entity.Children;
 entity.Children=null;

  _context.Parents.Add(entity);
 await _context.SaveChangesAsync();

foreach( var child in children)
{
         child.ParentId=entity.Id;
         _context.Children.Add(child);
     await _context.SaveChangesAsync();
}

我不确定性能会下降多少,但是如果顺序更重要,您可以尝试。


推荐阅读