2014-10-28 103 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