【问题标题】:Repository does not initialize entity data存储库不初始化实体数据
【发布时间】:2017-04-06 11:01:40
【问题描述】:

我想使用存储库模式创建包含实体框架数据的详细信息视图。

这是我的接口存储库:

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 错误,要么只显示数据的名称。

【问题讨论】:

  • 你需要初始化你的数据上下文,这通常在构造函数中完成
  • 我会远离存储库模式。
  • 你会推荐什么,因为它仍然不起作用?我只想在详细信息视图中包含多个实体数据表

标签: c# asp.net-mvc entity-framework repository repository-pattern


【解决方案1】:

创建初始化数据上下文的构造函数:

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

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

这允许您在没有参数的情况下初始化您的存储库,这些参数将初始化您的数据上下文或指定您自己的数据上下文。

您现在可以像这样使用它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2015-01-23
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多