我在ef-core2.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‘上配置密钥。如果不打算将“PermitPublication”包含在模型中,请确保它不包含在上下文中的DbSet属性中,不包含在对ModelBuilder的配置调用中,也不包括在模型中包含的类型上的导航属性中。如果没有显示LazyLoadingProxy禁用错误。
发布于 2018-05-31 17:36:28
正如错误消息所指出的,不能将PK配置为派生类型(该类型可以来自实体继承策略映射,而且显然现在也是代理类型,尽管后者可能是一个bug)。
在EF术语中(以及EF内部KeyAttributeConvention的源代码)意味着像EntityType.BaseType == null
这样的适用标准。
因此,您所需要的只是按以下方式修改if
标准:
if (entityTypeBuilder.Metadata.HasClrType() && entityTypeBuilder.Metadata.BaseType == null)
https://stackoverflow.com/questions/50628053
复制相似问题