1
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

4

1 回答 1

2

您的方法设计需要设置 shadow 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();
于 2019-03-08T11:08:27.440 回答