Reputation: 33
I use the Repository pattern in my project. Every component has a Bll class.
I want to create a base bll class, the sub Bll class can work without the same Repository Curd method.
language:c#
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class , IEntity
{
protected string ConnectionStringName;
protected IDatabase Db;
public Repository(string connStringName)
{
ConnectionStringName = connStringName;
Db = new Database(ConnectionStringName);
}
public Repository()
{
ConnectionStringName = "DefaultConnection";
Db = new Database(ConnectionStringName);
}
}
public abstract class BaseBll
{
protected Repository<IEntity> DefaultRepository;
protected BaseBll(Repository<IEntity> repository)
{
_defaultRepository = repository;
}
protected virtual List<IEntity> GetAll()
{
return DefaultRepository.GetAll();
}
}
public class DriverRepository : Repository<Driver>
{
public Driver GetDriverByLicenseNumber(string licenseNumber)
{
return Db.SingleOrDefault<Driver>("where LicenseNumber = @0", licenseNumber);
}
}
public class DriverBll
{
public DriverBll()
{
DefaultRepository = new DriverRepository();
//***Throw the Cannot convert ... to ... Error. Why?****
}
}
But...
Upvotes: 2
Views: 2462
Reputation: 10538
You have no zero-parameter constructor in Repository
, but DriverRepository
inherits from it. Because you have no zero-parameter constructor in Repository
, when DriverRepository
tries to create itself, it has no constructor to call on Repository
. You need to invoke the Repository(connectionString)
constructor from DriverRepository
's constructor like so.
public DriverRepository(string connectionString) : base(connectionString)
{
...
}
or
public DriverRepository() : base("YourConnectionString")
{
...
}
EDIT: Upon clarification.
Firstly in this code example, DriverBll
does not extend from BaseBll
, so it doesnt' know about the DefaultRepository
property. Secondly, Driver
must be implementing IEntity
.
Upvotes: 1