Expert wanna be
Expert wanna be

Reputation: 10624

Why I can not call base constructor method with an argument?

public class GenericRepository<TEntity> where TEntity : class
{
    internal DbContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(DbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }
    //snip
}

public class MyRepository<TEntity> where TEntity : GenericRepository<TEntity>
{
        public MyRepository(DbContext context) : base(context){ }
        //snip
}

I extended the GenericRepository class, and to use base's member variables I need to call Base's constructor in child's constructor. But I got an error that says:

'object' does not contain a constructor that takes 1 arguments

Even though the GenericRepository has constructor.

What am I doing wrong?

Upvotes: 3

Views: 140

Answers (2)

isxaker
isxaker

Reputation: 9456

You have to change MyRepository's base class to GenericRepository<TEntity> Also you need to leave where TEntity : class restriction

public class MyRepository<TEntity> : GenericRepository<TEntity> where TEntity : class
{
    public MyRepository(object context)
        :base(context)
    {

    }
}

Upvotes: 3

D Stanley
D Stanley

Reputation: 152556

Because your "base class" is object, not GenericRepository<TEntity>. You added a constraint on TEntity, you did not inherit from GenericRepository<TEntity>. Maybe you meant this:

public class MyRepository<TEntity> : GenericRepository<TEntity> where TEntity : class
{
    public MyRepository(DbContext context) : base(context){ }

Upvotes: 11

Related Questions