首页 > 解决方案 > EntityTypeConfiguration 中没有忽略属性?

问题描述

我有一个带有基类列表的简单实体类,在模型中被忽略:

public class MyClass
{
    public int Id {get;set;}
    public List<BaseChild> BaseChildren {get; set;}
}

具有以下配置:

public class MyClassConfiguration : IEntityTypeConfiguration<MyClass>
{
    public void Configure(EntityTypeBuilder<MyClass> builder)
    {
        builder.Property(o => o.Id).UseHiLo();
        builder.HasKey(o => o.Id);
    
        builder.Ignore(o => o.BaseChildren);
    }
}

我有从 BaseChild 继承的类,它们都使用这种配置:

public abstract class BaseChild
{
    public int MyClassId { get; set; }
}

public abstract class BaseChildConfiguration<T> : IEntityTypeConfiguration<T> where T : BaseChild
{
    public virtual void Configure(EntityTypeBuilder<T> builder)
    {
        builder.HasKey(o => o.MyClassId);
        builder.HasOne<MyClass>()
            .WithOne()
            .HasForeignKey<T>(o => o.MyClassId);
    }
}

public class Instance : Component
{
    public long Code { get; set; }
}

public class InstanceConfiguration : BaseChildConfiguration<Instance>
{
}

所有配置都正确应用在我的 OnModelCreating 中:

protected override void OnModelCreating(ModelBuilder mb)
{
    mb.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}

然而由于某种原因,我不断收到以下异常:

无法在“实例”上配置密钥,因为它是派生类型。必须在根类型“BaseChild”上配置密钥。如果您不打算将“BaseChild”包含在模型中,请确保它不包含在上下文的 DbSet 属性中、在对 ModelBuilder 的配置调用中引用或从包含的类型的导航属性中引用在模型中。

标签: entity-frameworkentity-framework-coreef-core-3.1

解决方案


推荐阅读