Search code examples
c#entity-framework-coreef-core-5.0ef-core-6.0

What is the equivalent of entityEntry.Metadata.DefiningNavigationName() in EF Core 6?


I am using EF Core 5 and I have the following in my DBContext SaveChanges():

            if (entityEntry.Metadata.Name == "ArticleBankAggregate.ArticleTag" && entityEntry.Metadata.DefiningNavigationName != "Tags")
            {
                entityEntry.Property("UpdatedDate").CurrentValue = DateTime.Now;

                if (entityEntry.State == EntityState.Added)

                {
                    entityEntry.Property("CreatedDate").CurrentValue = DateTime.Now;
                }
            }

To update a shadow property.

I am trying to upgrade to EF Core 6 and I get the following:

CS0618: 'IReadOnlyEntityType.DefiningNavigationName' is obsolete: 'Entity types with defining navigations have been replaced by shared-type entity types'

I cant find any examples or understand how to change this to use shared-type entities.


Solution

  • Shared entity types are entity types which use common CLR type (class), and are identified by the entity type name (since the type is not enough).

    Owned entity types now are implemented as shared types. The name of owned entity type consists of the name of the owner type + navigation property + type name. e.g. something like {Namespace}.{OwnerType}.{Navigation}#{OwnedType}.

    So one way to adjust the above code is check the name of the entity in interest and just test directly for it. Another way closer to what are you doing before is to check the CLR type and in case it is owned, the navigation property name from owner to owned (the equivalent of the "defining navigation name"), which can be obtained with FindOwnership().PrincipalToDependent.Name, e.g. something like

    if (entityEntry.Metadata.ClrType == typeof(ArticleTag)
        && entityEntry.Metadata.FindOwnership()?.PrincipalToDependent?.Name != "Tags")