【问题标题】:EF core custom Conventions and proxiesEF 核心自定义约定和代理
【发布时间】:2018-05-31 15:39:27
【问题描述】:

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

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

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

无法在“PermitPublicationProxy”上配置密钥,因为它是 派生类型。必须在根类型上配置密钥 '许可出版'。如果您不打算让“PermitPublication” 被包含在模型中,确保它不包含在 DbSet 中 上下文中的属性,在配置调用中引用 模型构建器,或从某个类型的导航属性中引用 包含在模型中。 如果 LazyLoadingProxy 禁用错误未显示。

【问题讨论】:

    标签: c# entity-framework-core ef-core-2.0


    【解决方案1】:

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

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

    因此,您只需修改if 条件,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      相关资源
      最近更新 更多