user3086843
user3086843

Reputation: 33

c# Generic cannot convert source type to target type

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.

But It appears the "Cannot convert ..DriverRepository to target type ...Repository IEntity>"

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

Answers (1)

Dan
Dan

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

Related Questions