Search code examples
c#databaseentity-frameworkcode-first

If I change the Navigation Property for the Parent Entity in a class, do I need to manually change the Foreign Key?


I have an Entity;

public class ChildEntity
{
    /// <summary>
    /// Foreign key for this entity.
    /// </summary>
    public virtual int ParentId { get; set; }

    /// <summary>
    /// Navigation Property for this entity.
    /// </summary>
    public virtual TParentEntity Parent { get; set; }
}

If I am changing the Parent property to a different ParentEntity in the Database, (updating both Parents Collections of Children Entities) do I then need to change the ParentId from one Parent Entity to the other manually?

Thanks!


Solution

  • If you change the navigation property of an entity, the corresponding changes will be made to the foreign key column in the database.

    source: https://learn.microsoft.com/en-us/ef/core/saving/related-data#changing-relationships

    Here's a sample code to observe the said behavior.

    using (var context = new Context())
    {
        var child = new ChildEntity();
        child.Parent = new TParentEntity();
        context.Add(child);
    
        context.SaveChanges();
        Console.WriteLine(child.ParentId); // ParentId == 1
    
        child.Parent = new TParentEntity();
        Console.WriteLine(child.ParentId); // ParentId == 1
    
        context.SaveChanges();
        Console.WriteLine(child.ParentId); // ParentId == 2
    }