Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find foreign key field for navigation property?

For a given entity I can get all its references by calling

var references = dbContext.Entry(entity).References;

Now I want to set all references to null.

foreach (var reference in references)
{
  reference.CurrentValue = null;
}
context.Update(entity);
context.SaveChanges();

But apparently it is not sufficient to set the reference to null, one must set the foreign key property as well. But how to find the foreign key field for a given reference?

like image 759
user2900970 Avatar asked Oct 27 '25 10:10

user2900970


1 Answers

You can use Metadata property to get the associated INavigation, then ForeignKey property to get the associated IForeignKey, then the Properties property to get the associated properties of type IProperty, and finally the Name property which can be passed to Property method to obtain the associated PropertyEntry for manipulating the value.

Putting all that in action:


var entry = dbContext.Entry(entity);
foreach (var reference in entry.References)
{
    reference.CurrentValue = null;
    foreach (var fkProperty in reference.Metadata.ForeignKey.Properties)
        entry.Property(fkProperty.Name).CurrentValue = null;
}

Update: In recent EF Core versions the Metadata property type has been changed to INavigationBase (probably as part of a preparation of skip navigation properties support) which has no ForeignKey property, hence you need to manually cast it to the aforementioned INavigation interface, e.g.

using Microsoft.EntityFrameworkCore.Metadata;
...
foreach (var fkProperty in ((INavigation)reference.Metadata).ForeignKey.Properties)
...
like image 125
Ivan Stoev Avatar answered Oct 30 '25 13:10

Ivan Stoev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!