EF Core 更新导航 属性 但 FK 隐藏 属性 未更新

EF Core update navigation property but FK hidden property not update

public class Location
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("Name")]
    [Required]
    public string Name { get; set; }

    [JsonProperty("Address")]
    public string Address { get; set; }

    public NpgsqlTsVector SearchVector { get; set; }

    /**
    Navigation Property
     */

    public Location ParentLocation { get; set; }

    [JsonProperty("Children")]
    public virtual ICollection<Location> ChildrenLocation { get; set; }

}

此自引用实体 class 在数据库中生成字段 "ParentLocationId"(隐藏键)。

当我使用以下代码更新时添加..

    public async Task<Location> UpdateLocation(Location location, int? moveToParentLocation)
    {
        // this work
        // _context.Entry(location).Property("ParentLocationId").CurrentValue = moveToParentLocation;

        // this not work
        _context.Entry(location).Reference(loc => loc.ParentLocation).CurrentValue = null;

        _context.Locations.Update(location);

        await _context.SaveChangesAsync();

        return location;
    }

Reference() 不起作用,因为我不想用 Property() 硬编码数据库字段我做错了什么。

PS。发送到此方法的位置尚未附加到 DBContext

您的方法设计需要设置阴影 FK 属性。如果您不想对名称进行硬编码,可以使用 NavigationEntry.Metadata 属性 查找 FK 属性 名称并将其用于 Property 方法。

像这样:

var entry = _context.Update(location);

var parentLocationProperty = entry.Property(
    entry.Reference(loc => loc.ParentLocation).Metadata.ForeignKey.Properties[0].Name
);
parentLocationProperty.CurrentValue = moveToParentLocation;

await _context.SaveChangesAsync();