2014-10-28 101 views
2

我试图松散地耦合这段代码,但我不知道该如何或者应该如何。与实体框架的松散耦合

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

'System.Data.Entity.DbContext' does not contain a definition for 'TMeasures' and no extension method 'TMeasures' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?)

有人可以帮助我吗?

谢谢!

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; 
    } 
} 
+0

我不能用什么方式,这可能被视为看“松散耦合”,它似乎破碎了。你最终的目标是什么?你想编写一个可以与任何DbContext一起工作的repo,而不是从DbContext派生的特定类。如果是谷歌的“通用知识库”,我知道我已经发布过去的例子。 – 2014-10-28 16:27:34

+0

Mati(下图)为我解决了我的问题。它显然已经坏了,但我说的是不必在类中实例化一个实体类。我宁愿将实体对象传递给类本身。 – 2014-10-29 14:31:34

回答

2

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

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

然后用此背景下,而不是一般的一个:

class MeasureRepository : IMeasureRepository 
{ 
    private MeasuringContext db; 

    //... 
} 
+0

我想这将允许我改变MeasureRepository类正在接收的上下文,如果将来需要的话? – 2014-10-28 16:49:36

+0

如果你想要的是一个通用的上下文,那么这个问题可能会有所帮助:[通用访问DbContext](http://stackoverflow.com/questions/18151143/generic-access-to-dbcontext) – 2014-10-28 16:52:46