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