简体   繁体   中英

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

}

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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