Aleksa Kojadinovic
Aleksa Kojadinovic

Reputation: 337

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

Upvotes: 3

Views: 131

Answers (1)

David Pilkington
David Pilkington

Reputation: 13620

You need to add a class constraint

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

Upvotes: 3

Related Questions