我在 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;
}
}
一切正常,但有时我会出错:
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)
关于c# - EF 核心自定义约定和代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628053/