【问题标题】:Add private field from abstract class to migration将抽象类中的私有字段添加到迁移
【发布时间】:2019-07-28 14:29:10
【问题描述】:

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

属性“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 的访问级别更改为受保护或内部,它们都导致了相同的错误。但是,将其更改为 public 正确构建了迁移,包括 ChildClass 自己的私有字段。

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

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

【问题讨论】:

  • 如果add-migration 不知道它存在,因为它在你的编译之外,它怎么知道访问它?
  • 我的 DBContext 中有public DbSet&lt;ChildClass&gt; Child { get; set; },它之前检测到我的班级很好。添加私有字段是一种修改。我还尝试将base() 添加到internal ChildClassConfiguration() : base(),结果没有变化。

标签: c# asp.net entity-framework ef-code-first


【解决方案1】:

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

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

【讨论】:

  • 我已经尝试让 BaseField 受到保护,结果没有改变。使其公开有效,但这会暴露我不想在调用程序中暴露的信息。
猜你喜欢
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多