簡體   English   中英

EF核心自定義約定和代理

[英]EF core custom Conventions and proxies

我在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”上配置密鑰。 如果您不打算將“PermitPublication”包含在模型中,請確保它不包含在上下文中的DbSet屬性中,在模型構建器的配置調用中引用,或者從包含的類型的導航屬性中引用在模型中。 如果未顯示LazyLoadingProxy禁用錯誤。

正如錯誤消息所示,無法為派生類型配置PK(可能來自實體繼承策略映射,顯然現在也是代理類型,盡管后者可能是錯誤)。

在EF Core術語中(以及EF Core內部KeyAttributeConvention的源代碼)表示適用的標准,如EntityType.BaseType == null

所以你需要的是修改if標准,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM