问题
I have a Generic Repository class, see below, which is used to perform common Data Access functions, ie, Add, GetByID etc.
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
internal GolfEntities context;
internal DbSet<TEntity> dbSet;
public GenericRepository(GolfEntities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public TEntity GetByID(object id)
{
return dbSet.Find(id);
}
I would like to create another Repository class that derives from this Generic Repository class so that I can carry out other functions which do not belong to the Generic Repository class, such as, get a users full name.
I have created a a class called UserRepository, see below, which derives from the Generic Repository, however, I keep getting an error when I compile:
Repository.GenericRepository< User> does not contain a constructor that takes 0 arguments
public class UserRepository : GenericRepository<User>, IUserRepository
{
internal GolfEntities _context;
public UserRepository() : base() { }
public UserRepository(GolfEntities context)
{
_context = context;
}
public string FullName()
{
return "Full Name: Test FullName";
}
}
Does anyone know how to fix this?
Any help would be much appreciated.
Thanks.
回答1:
You should remove the default constructor from your derived repository:
public UserRepository() : base() { }
Since your base repository class doesn't have a parameterless constructor calling base()
doesn't make sense. Also you don't need to repeat the same logic in your derived constructor as in the base one. You could only invoke it:
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(GolfEntities context): base(context)
{
}
public string FullName()
{
return "Full Name: Test FullName";
}
}
回答2:
Change your UserRepository to this:
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(GolfEntities context)
: base (context)
{
}
public string FullName()
{
return "Full Name: Test FullName";
}
}
Your GenericRepository does not have a default constructor so you need to call the constructor which is expecting your GolfEntities context and pass the parameter down.
回答3:
The base (generic) repository does not have a parameterless, default constructor and so you cannot write this:
public UserRepository() : base() { }
You need to call one of the base class constructors.
来源:https://stackoverflow.com/questions/9601057/class-derived-from-generic-repository