c# - 存储库不初始化实体数据

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

我想使用存储库模式创建包含 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/

相关文章:

c# - MySQL实时更新异常

c# - 在 C# 整数运算中,a/b/c 是否总是等于 a/(b*c)?

c# - Entity Framework 代码优先 - 从表中选择对象,其中对象的类型位于预定义列表中

c# - JSON 自动完成,不显示结果

c# - FluentValidation 和 Entity Framework 查找

c# - 附加类型的实体失败,因为相同类型的另一个实体已经具有相同的主键值

c# - 在 Screen Scraping 中工作时出现页面发布问题

c# - 在 C# 中操作 RegEx 匹配以进行计算

c# - ASP.NET MVC - 如何设计动态 H1/标题方案?

C# Razor 语法 - html.display 用于显示为文本,而不是 html