EF core custom Conventions and proxies

c# ef-core-2.0 entity-framework-core

Question

I create a custom IEntityTypeAddedConvention in ef-core 2.1 and enable LazyLoadingProxies by calling UseLazyLoadingProxies method. My custom convention is a class to add composite key to model as below:

public class CompositeKeyConvetion : IEntityTypeAddedConvention
{
    public InternalEntityTypeBuilder Apply(InternalEntityTypeBuilder entityTypeBuilder)
    {
        Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));

        if (entityTypeBuilder.Metadata.HasClrType())
        {
            var pks = entityTypeBuilder
                .Metadata
                .ClrType
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => p.IsDefined(typeof(CompositeKeyAttribute), false))
                .ToList();

            if (pks.Count > 0)
            {
                entityTypeBuilder.PrimaryKey(pks, ConfigurationSource.Convention);
            }
        }

        return entityTypeBuilder;
    }
}

All things work perfectly but sometimes i get a error:

A key cannot be configured on 'PermitPublicationProxy' because it is a derived type. The key must be configured on the root type 'PermitPublication'. If you did not intend for 'PermitPublication' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model. If LazyLoadingProxy disabled error not shown.

1
1
5/31/2018 5:36:50 PM

Accepted Answer

As the error message indicates, the PK cannot be configured for a derived type (which could be from entity inheritance strategy mapping, and apparently now also a proxy type, although the later could be a bug).

Which in EF Core terms (and also the source code of the EF Core internal KeyAttributeConvention) means applicable criteria like EntityType.BaseType == null.

So all you need is to modify the if criteria as follows:

if (entityTypeBuilder.Metadata.HasClrType() && entityTypeBuilder.Metadata.BaseType == null)
3
5/31/2018 5:36:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow