2

我想使用存儲庫模式創建一個具有實體框架數據的Details視圖。存儲庫不初始化實體數據

這是我的接口庫:

public interface InterfaceRepositroy: IDisposable 
{ 
    IEnumerable<SubjectContent> GetAll(); 
    SubjectContent Get(string id); 
} 

這是toher庫:

public class SubjectRepository : InterfaceRepositroy,IDisposable 
{ 
    private irfwebpage20161013070934_dbEntities2 db; 

    public IEnumerable<SubjectContent> GetAll() 
    { 
     return db.Set<SubjectContent>().ToList(); 
    } 
    public SubjectContent Get(string id) 
    { 
     return db.Set<SubjectContent>().Find(id); 
    } 

    public void Dispose() 
    { 
     throw new NotImplementedException(); 
    } 
} 

這裏是我的控制器:

private InterfaceRepositroy subjectreposi; 

public ActionResult Details(string id) 
{ 
    SubjectContent subject = subjectreposi.Get(id); 
    return View(subject); 
} 

我的看法是一個標準的詳細信息模板。

它會得到一個錯誤在控制這一點:

SubjectContent subject = subjectreposi.Get(id); 

我會很感激的幫助。這就像我試圖實現的存儲庫模式的第四個版本,但目前爲止它們都沒有工作。我已經嘗試過,沒有接口,使用subjecrepository的實例,或者在存儲庫中使用不同的linq to sql。它要麼發生http錯誤,要麼不顯示數據只是數據的名稱。

+0

你需要初始化你的數據上下文,這在構造 –

+0

我會留從存儲庫模式遠通常完成。 –

+0

你會推薦什麼,因爲它仍然不起作用?我只是想在細節視圖中的多個實體數據表 –

回答

1

創建初始化數據方面的構造函數:

public SubjectRepository() 
{ 
    db = new irfwebpage20161013070934_dbEntities2(); 
} 

public SubjectRepository(irfwebpage20161013070934_dbEntities2 dbContext) 
{ 
    db = dbContext; 
} 

這可以讓你要麼不帶參數,這將初始化你的數據上下文或指定自己的數據上下文初始化存儲庫。

現在你可以使用這個像這樣:

var repo = new SubjectRepository(); 
SubjectContent subject = repo.Get(id);