user2900970
user2900970

Reputation: 761

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?

Upvotes: 4

Views: 1564

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205719

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)
...

Upvotes: 5

Related Questions