Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

c# - 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.

question from:https://stackoverflow.com/questions/65840060/dbcontext-and-dbset-issues-in-generic-repository

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...