EF 核心自定义约定和代理



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

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

所有事情都运行良好,但有时我会收到错误:

无法在"允许发布代理"上配置密钥,因为它是 派生类型。 必须在根类型上配置密钥 "许可发布"。 如果您不打算"允许发布" 包含在模型中,确保它不包含在 DbSet 中 上下文中的属性,在配置调用中引用 模型构建器,或从 包含在模型中。 如果延迟加载代理禁用错误未显示。

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

在 EF Core 术语(以及 EF Core 内部 KeyAttributeConvention 的源代码(中,这意味着适用的条件,如EntityType.BaseType == null

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

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

最新更新