发布
社区首页 >问答首页 >EF核心定制公约和代理

EF核心定制公约和代理
EN

Stack Overflow用户
提问于 2018-05-31 15:39:27
回答 1查看 646关注 0票数 1

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

代码语言:javascript
代码运行次数:0
复制
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禁用错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-31 17:36:28

正如错误消息所指出的,不能将PK配置为派生类型(该类型可以来自实体继承策略映射,而且显然现在也是代理类型,尽管后者可能是一个bug)。

在EF术语中(以及EF内部KeyAttributeConvention的源代码)意味着像EntityType.BaseType == null这样的适用标准。

因此,您所需要的只是按以下方式修改if标准:

代码语言:javascript
代码运行次数:0
复制
if (entityTypeBuilder.Metadata.HasClrType() && entityTypeBuilder.Metadata.BaseType == null)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50628053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档