[英]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.