Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic repository issue

I am trying to implement the generic repository pattern in my application. I have two interfaces, IEntity and IRepository:

IEntity:

public interface IEntity
{
    int Id { get; set; }
}

IRepository:

public interface IRepository<T> where T : IEntity
{
    void AddOrUpdate(T ent);
    void Delete(T ent);
    IQueryable<T> GetAll();
}

And now I'm trying to make a generic RepositoryGlobal class, but I am getting this error:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method

This is what my code looks like:

public class RepositoryGlobal<T> : IRepository<T> where T : IEntity
{

    public RepositoryGlobal(DbContext _ctx)
    {
        this._context = _ctx;
    }

    private DbContext _context;

    public void Add(T ent)
    {
        this._context.Set<T>().Add(ent);
    }

    public void AddOrUpdate(T ent)
    {
        if (ent.Id == 0)
        {
            //not important
        }else
        {
            //for now
        }
    }
    public void Delete(T ent)
    {

    }
    public IQueryable<T> GetAll()
    {
        return null;
    }

}

The error appears in the Add method of the RepositoryGlobal class. Any ideas? Thanks

like image 386
Aleksa Kojadinovic Avatar asked Jul 23 '26 00:07

Aleksa Kojadinovic


1 Answers

You need to add a class constraint

public class RepositoryGlobal<T> : IRepository<T> where T : class, IEntity
like image 65
David Pilkington Avatar answered Jul 25 '26 14:07

David Pilkington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!