【问题标题】:Extending or overriding a model from Base从 Base 扩展或覆盖模型
【发布时间】:2018-01-30 19:36:06
【问题描述】:

我正在尝试将新属性添加到模型中,该模型是我从 nuget 安装的 Base 库,并尝试在安装 Base 的项目中添加新属性

基础模型

public class Product
{
  int Id{ get; set; }
  string Name{ get; set; }
  string Status{ get; set; }
}

在我的项目中,我想在不更改模型名称的情况下添加一个名为 Code (string) 的新属性

我尝试通过继承基本上下文并忽略基本模型来做到这一点,如下所示

public class PDataContext : DataContext
    {
        public PDataContext() : base()
        {
            Configuration.LazyLoadingEnabled = false;            
            Database.SetInitializer<PDataContext>(null);
        }

        public new DbSet<Product> Products { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();            
            modelBuilder.Ignore<ClientApi.Base.Models.Product>();
        }
    }

上面没有工作,因为它抛出了一个异常"The entity type Product is not part of the model for the current context."

我可以知道最好的方法吗?

【问题讨论】:

  • 您忽略了模型的 Product 类型,因此您的 DbSet 必须具有不同的类型,或者您必须删除 Ignore 语句(为了查询,您仍然必须编辑类型使其具有附加属性)

标签: c# entity-framework model


【解决方案1】:

您没有在帖子中包含它,但我假设您要使用的实体继承自 Product 并包含一个额外的属性 Code 类似这样的东西?

public class MyProduct : Product
{
    public string Code { get; set; }
}

在这种情况下,您可以在上下文中使用MyProduct 而不是Product

public class PDataContext : DataContext
{
    public PDataContext() : base()
    {
        Configuration.LazyLoadingEnabled = false;            
        Database.SetInitializer<PDataContext>(null);
    }

    public new DbSet<MyProduct> Products { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<MyProduct>().ToTable("Product");
    }
}

【讨论】:

  • 不,我还是尽量不改表名
  • @Dolt 请立即查看答案,我添加了一行以保持表名相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多