繁体   English   中英

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; }

}

此自引用实体类在数据库中生成字段“ 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM