Reputation: 5637
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; }
}
this self referencing entity class generate field "ParentLocationId" in the database (Hidden key).
Add when I use the following code to update..
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()
doesn't work, and because I don't want to hardcode database field with Property()
what did I do wrong.
PS. Location sent to this method is not attached to DBContext
yet.
Upvotes: 1
Views: 261
Reputation: 205589
The design of your method requires setting the shadow FK property. If you don't want to hardcode the name, you could use the NavigationEntry.Metadata property to find the FK property name and use it for Property
method.
Something like this:
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();
Upvotes: 2