简体   繁体   中英

EF core custom Conventions and proxies

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM