【问题标题】:Loose coupling with entity framework与实体框架的松耦合
【发布时间】:2014-10-28 16:19:56
【问题描述】:

我正在尝试松散地耦合此代码,但我不确定如何或是否应该。

我正在使用实体框架,DbContext 是实体对象TMeasure 使用的继承类。当我运行此代码时,出现此错误:

“System.Data.Entity.DbContext”不包含“TMeasures”的定义,并且找不到接受“System.Data.Entity.DbContext”类型的第一个参数的扩展方法“TMeasures”(您是否缺少using 指令还是程序集引用?)

有人可以帮我解决这个问题吗?

谢谢!

class MeasureRepository: IMeasureRepository
{
    private DbContext db;

    public MeasureRepository(DbContext db)
    {
        this.db = db;
    }

    public List<TMeasure> GetAll()
    {
        var results = (from i in db.TMeasures
                        orderby i.strMeasure
                        select i).ToList();
        return results;
    }
}

【问题讨论】:

  • 我看不出这可以被认为是“松散耦合”,它似乎被打破了。你在这里的最终目标是什么?您是否要编写与任何 DbContext 一起使用的存储库,而不是与派生自 DbContext 的特定类一起使用。如果是谷歌“通用存储库”,我知道我过去曾发布过一个示例。
  • Mati(下)给了我解决问题的方法。它显然被破坏了,但我说的是不必在类中实例化实体类。我宁愿将实体对象传递给类本身。

标签: c# entity-framework entity loose-coupling


【解决方案1】:

您应该创建自己的上下文:

//Internal class recommended
public class MeasuringContext : DbContext
{
     public DbSet<Measure> Measures { get; set; }
}

然后使用这个上下文而不是通用的:

class MeasureRepository : IMeasureRepository
{
    private MeasuringContext db;

    //...
}

【讨论】:

  • 我想这将允许我更改 MeasureRepository 类正在接收的上下文,如果将来需要的话?
  • 如果您想要的是通用上下文,那么这个问题可能会有所帮助:Generic access to DbContext
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 2013-08-01
  • 2017-05-09
  • 1970-01-01
相关资源
最近更新 更多