c# - EF 核心自定义约定和代理

标签 c# entity-framework-core ef-core-2.0

我在 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/

相关文章:

c# - 如何在不使用关键字的情况下使用枚举实例化对象时编写更清晰的代码?

c# - EF Core 2 使用 OUTPUT 参数执行存储过程

c# - 如何使用Net Core获取DbContext中的用户信息

c# - Entity Framework Core 2 一对一关系 "on one table"

c# - 将 Rx 与 Prism 的 EventAggregator 一起使用或与其一起使用 - 建议的方法?

c# - 是否可以将命令绑定(bind)到资源?

c# - 将 Web API 用于 Windows 服务以通过轮询接收命令和执行任务?

c# - 跳过导航没有定义外键

entity-framework - EntityFrameworkCore - 启用 DbContextPool 时如何注入(inject) IPrincipal

asp.net-core - Net core MVC 整洁的架构,没有存储库模式