没有给出的参数对应于GenericRepository <Incident> .GenericRepository(dbContext)所需的形式参数'上下文

ASP*_*450 18 model-view-controller entity-framework repository-pattern

我收到此错误消息时,尝试从我的GenericRepository继承.错误说我还需要提供一个上下文,但我不确定如何?

//IncidentRepository 
public class IncidentRepository : GenericRepository<Incident>

//Generic Repository (to inherit from)
public class GenericRepository<TEntity> where TEntity : class
{
internal db_SLee_FYPContext context;
internal DbSet<TEntity> dbSet;

public GenericRepository(db_SLee_FYPContext context)
{
    this.context = context;
    this.dbSet = context.Set<TEntity>();
}
Run Code Online (Sandbox Code Playgroud)

编辑:

只是为了检查我已经掌握了这个?

  public class IncidentRepository: GenericRepository<Incident>
  {

    public IncidentRepository(db_SLee_FYPContext context)
    {
        this.context = context;
    }

    //Then in my genric repository
    public GenericRepository()
    {

    }
Run Code Online (Sandbox Code Playgroud)

Ger*_*old 32

该错误告诉您不要调用适当的基础构造函数.派生类中的构造函数......

public IncidentRepository(db_SLee_FYPContext context)
{
    this.context = context;
}
Run Code Online (Sandbox Code Playgroud)

......其实这样做:

public IncidentRepository(db_SLee_FYPContext context)
    : base()
{
    this.context = context;
}
Run Code Online (Sandbox Code Playgroud)

但是没有无参数的基础构造函数.

你应该通过调用匹配的基础构造函数来解决这个问题:

public IncidentRepository(db_SLee_FYPContext context)
    : base(context)
{ }
Run Code Online (Sandbox Code Playgroud)

在C#6中,如果基类型中只有一个构造函数,则会收到此消息,因此它为您提供了最佳提示,即基本构造函数中缺少哪个参数.在C#5中,消息就是这样

GenericRepository不包含带0参数的构造函数

  • 不错的答案;我希望错误消息(在这个问题的标题中看到)使用了“构造函数”这个词,因为问题(和修复)的来源会更明显 (2认同)