How to find foreign key field for navigation property?

Viewed 653

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?

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