【问题标题】:using the dbset of Inherited class使用继承类的 dbset
【发布时间】:2013-07-26 11:50:45
【问题描述】:

假设我有一门课食物

public class FoodsContext : DbContext, IUnitOfWork
{
   public DbSet<Consumer> Consumers {get; set;}
}

还有类Fruits

public class FruitsContext: FoodsContext
{
   public DbSet<Price> Prices {get; set;}
}

然后在我的存储库中 假设我有

public class SampleRepository
{
   private readonly FruitsContext _dbFruits = new FruitsContext();

   public void foo()
   {
      _dbFruits.Prices.doanything;
      //how can i use Consumers table that has been set in Foods class
   }
}

在我的存储库类中,我想访问 Consumers 表中的值,而不创建 Food 类的实例。我该怎么做?

我在某个项目中看到过这个,但我现在不太记得了。有人可以提出一些建议吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 dbset


    【解决方案1】:

    在我看来,这就像简单的继承:

    public void foo()
    {
      _dbFruits.Prices.doanything;
      //how can i use Consumers table that has been set in Foods class
      _dbFruits.Consumers.doanything;  // this should work
    }
    

    【讨论】:

    • 这可能有效,但我发布了一个也有效的答案
    【解决方案2】:

    你也可以

    public void foo()
    {
      _dbFruits.Prices.doanything;
      //how can i use Consumers table that has been set in Foods class
      _dbFruits.Set<Consumer>.doanything;
    }
    

    【讨论】:

    • 是的,这是一个 DbContext 方法。另一个基类。
    • 但是请检查您的设计,并可能复制一些经过更多设计的内容。而且 UnitOfWork 通常拥有 1 个或多个 Repositories,它不是它们的基类。
    • 其实我的设计要复杂得多,我只是想在这里展示基本的随机类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多