-1

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.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
XDev
  • 125
  • 1
  • 8

1 Answers1

1

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.

user1672994
  • 10,509
  • 1
  • 19
  • 32
  • I still have these errors https://imgur.com/qyTaIxZ – XDev Jan 22 '21 at 06:58
  • 1) The constraint should be defined at both interface and class implementation. 2) Your method `GetTable` is having return type as void? Should it not be the appropriate type. – user1672994 Jan 22 '21 at 08:00
  • massive thanks sir this is very helpful, I appreciate this for you sir, but I have a small note about your answer I didn't need to send the connection string to the `DBContext` it's work without the `connection string` – XDev Jan 22 '21 at 09:37