从抽象类添加私有字段到迁移

问题描述 投票:0回答:1

我有一个带有私有字段的抽象基类,我想为每个继承类添加到我的数据库中。我目前收到以下错误

属性“BaseField”不是“ChildClass”类型的声明属性。使用Ignore方法或NotMappedAttribute数据批注验证是否未从模型中显式排除该属性。确保它是有效的原始属性。

这是我当前(和期望的)设置:

public abstract class BaseClass
{
     private string BaseField{ get; set; }

     internal class BaseClassConfiguration<T> : EntityTypeConfiguration<T> where T : BaseClass
     {
         internal BaseLogbookConfiguration()
         {
             Property(p => p.BaseField);
         }
     }
}

public class ChildClass : BaseClass
{
    private string ChildField { get; set; }

    internal class ChildClass : BaseClassConfiguration<ChildClass>
    {
        internal ChildClass ()
        {
            Property(p => p.ChieldField);
        }
    }

}

然后,在我的DbContext中

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new ChildClass.ChildClassConfiguration());
 }

在执行add-migration my_migration时,我得到上面的错误。我已经尝试将BaseField的访问级别更改为protected或internal,它们都会导致相同的错误。但是,将其更改为public正确构建了迁移,包括ChildClass自己的私有字段。

   AddColumn("dbo.ChildClass", "ChildField", c => c.String());
   AddColumn("dbo.ChildClass", "BaseField", c => c.String());

但是,我不希望我的库外的类能够直接访问BaseField。我怎么解决这个问题?

c# asp.net entity-framework ef-code-first
1个回答
0
投票

在您的代码示例中,类型ChildClass不包含名为BaseField.的字段或变量。它包含名为ChildField的字段。

我可以看到BaseClass包含一个BaseField,但它被标记为private,这意味着它不是继承的。如果您希望将其继承,请将其标记为受保护或公开。

© www.soinside.com 2019 - 2024. All rights reserved.