Search code examples
c#genericsrepository-patterngeneric-programming

DbContext and DbSet issues in Generic repository


I'm trying to create a project will play the repository role in all my projects.

The Idea:

The Idea was inspired from Generic Repository pattern, so I'm trying to create a generic class will be the repository. this class will receive the dbcontext at the Instantiation. this class will implement an Interface.

The Interface :

interface IRepo<Tcontext> where  Tcontext : DbContext
{
    void GetAll<Table>();
}

The Repo class :

public class Repo<Tcontext>:IRepo<Tcontext> where Tcontext: DbContext
{
    private Tcontext _Context { get; set; } = null;
    private DbSet    _Table   { get; set; } = null;


    public Repo()
    {
        _Context = new Tcontext();
    }
   

    public void GetAll<Table>()
    {
        _Table = new DbSet<Table>();

        return _Context.Set<Table>().ToList();
    }
}

So, the Idea, lets imagine we have this dbcontext class: DBEntities, and if I want to select all records from Client table, and after that in another line I Wanna select all records from Order table

I would use:

        Repo<DBEntities> repo = new Repo<DBEntities>();

       var clients repo.GetAll<Client>();
       var orders repo.GetAll<Order>();

What is the problem:

the problem in Repo class. the problem is four errors I don't have any Idea how can I solve them.

Errors: enter image description here

enter image description here

so please, any help to solve this problem? and massive thanks in advance.


Solution

  • The first two errors The Table must be a reference type.... is logged as you have not defined the constraints on your function. Change the signature as shown below; using the below signature the method is putting constraint that generic type Table should be reference type.

    public void GetAll<Table>() where Table : class
    

    The third error as there is no public default constructor for DBContext. You should use the parametrized one. Check the DBContext definition here

    _Context = new Tcontext(connectionString);
    

    The fourth error will resolve automatically after adding the changes for first two as generic parameter Table constraint is defined. You can check the signature of Set function at here.