EF 核心自定义约定和代理

EF core custom Conventions and proxies

我在 ef-core 2.1 中创建了自定义 IEntityTypeAddedConvention 并通过调用 UseLazyLoadingProxies 方法启用了 LazyLoadingProxies。 我的自定义约定是 class 向模型添加复合键,如下所示:

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

一切正常,但有时我会出错:

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.

如错误消息所示,无法为派生类型配置 PK(可能来自实体继承策略映射,现在显然也是代理类型,尽管后者可能是错误)。

在 EF Core 术语中(以及 EF Core 内部的源代码 KeyAttributeConvention)表示适用的标准,例如 EntityType.BaseType == null

所以您只需按如下方式修改 if 条件:

if (entityTypeBuilder.Metadata.HasClrType() && entityTypeBuilder.Metadata.BaseType == null)