我想使用存储库模式创建包含 Entity Framework 数据的详细信息 View 。
这是我的接口(interface)库:
public interface InterfaceRepositroy: IDisposable
{
IEnumerable<SubjectContent> GetAll();
SubjectContent Get(string id);
}
这是她的存储库:
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();
}
}
这是我的 Controller :
private InterfaceRepositroy subjectreposi;
public ActionResult Details(string id)
{
SubjectContent subject = subjectreposi.Get(id);
return View(subject);
}
我的 View 是一个标准的详细信息模板。
此时 Controller 出现错误:
SubjectContent subject = subjectreposi.Get(id);
非常感谢您的帮助。这就像我正在尝试实现的存储库模式的第四个版本,但到目前为止它们都没有用。我在没有接口(interface)的情况下尝试过,使用 subjecrepository 的实例或在存储库中使用不同的 linq to sql。它要么收到 http 错误,要么不只显示数据的名称。
最佳答案
创建初始化数据上下文的构造函数:
public SubjectRepository()
{
db = new irfwebpage20161013070934_dbEntities2();
}
public SubjectRepository(irfwebpage20161013070934_dbEntities2 dbContext)
{
db = dbContext;
}
这允许您在没有参数的情况下初始化您的存储库,这将初始化您的数据上下文或指定您自己的数据上下文。
您现在可以像这样使用它:
var repo = new SubjectRepository();
SubjectContent subject = repo.Get(id);
关于c# - 存储库不初始化实体数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747469/