更新实体框架中的子/嵌套实体

问题描述 投票:0回答:1

尝试在这里学习EF。我有一个非常基本的父子一对多关系,我正在尝试了解如何一次性更新父实体和子实体。

我尝试了很多不同的方法,但都有效。任何帮助将不胜感激。谢谢你。

父类和Dto

public partial class Parent
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Child> Children { get; set; } = new List<Child>();
}

子类和Dto

public partial class Child
{
    public Guid Id { get; set; }

    public Guid ParentId { get; set; }

    public virtual Parent Parent { get; set; }  <-- this is removed in the Child Dto

    public string Name { get; set; }
}

有效负载

{
    "id": "bcf2678e-a318-4cc7-a8d0-1c1d887d4f8c",
    "name": " **New Value here** ",
    "children": [
        {
            "id": "1750c5a7-0845-49b8-9cae-064d5a03ef5f",
            "parentId": "bcf2678e-a318-4cc7-a8d0-1c1d887d4f8c",
            "name": " **New Value here** "
        },
        {
            "id": "77ffdbc9-3bc3-4569-9703-4b08187145dc",
            "parentId": "bcf2678e-a318-4cc7-a8d0-1c1d887d4f8c",
            "name": " **New Value here** "
        }
    ]
}

错误

{
    "statusCode": 500,
    "message": "The association between entity types 'Parent' and 'Child' has been severed, but the relationship is either marked as required or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, configure the relationship to use cascade deletes. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.",
}

控制器

[HttpPost("SetParent")]
public async Task<ActionResult<ParentDto>> SetParent(ParentDto parentDto)
{
    var parent = await _context.Parents
        .Where(f => f.Id == parentDto.Id)
        .Include(f => f.Children)
        .SingleOrDefaultAsync();

    if (parent == null) return NotFound();

    _mapper.Map(parentDto, parent);

    await _context.SaveChangesAsync();
    
    return Ok(parentDto);
}
entity-framework asp.net-core automapper
1个回答
0
投票

感谢@XinranShen,解决此问题的方法是将 OnDelete 行为更改为 Cascade,就像错误所说的那样。

因此将删除行为从

更改为
modelBuilder.Entity<Child>(entity =>
        {
            entity.ToTable("Child", "Tools");
            entity.HasOne(d => d.Parent).WithMany(p => p.Children)
                 .HasForeignKey(d => d.ParentId)
                 .OnDelete(DeleteBehavior.ClientSetNull);
        });

modelBuilder.Entity<Child>(entity =>
        {
            entity.ToTable("Child", "Tools");
            entity.HasOne(d => d.Parent).WithMany(p => p.Children)
                 .HasForeignKey(d => d.ParentId)
                 .OnDelete(DeleteBehavior.Cascade);
        });
© www.soinside.com 2019 - 2024. All rights reserved.