1

Hello im trying to build a generic repository on top of linq2sql. I have a interface for the generic repository:

 public interface IRepository<T> where T : class
    {
        void Update(T entity);
        T CreateInstance();
        void Delete(int id);
        T Get(int id);
        List<T> GetAll();
        List<T> GetAll(Func<T, bool> expr);
    }

I have an implementation of this too. Now i have made a connection through linq2sql to my database and gotten 2 classes, "Car" and "House", now i want to make a specialized repository for car:

public interface ICarRepository<Car> : IRepository<Car>
    {        
    }

Now i get the error that: The type 'Car' must be a reference type in order to use it as parameter 'T' in the generic type or method 'GenericRepository.Repository.IRepository<T>'

How come i get that error, this is the signature of the "Car" class:

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Car")]
    public partial class Car : INotifyPropertyChanging, INotifyPropertyChanged
    {...}
jv42
  • 8,521
  • 5
  • 40
  • 64
Brian Hvarregaard
  • 4,081
  • 6
  • 41
  • 77
  • Look at http://stackoverflow.com/questions/1992443/why-do-i-get-error-must-be-a-reference-type-in-my-c-sharp-generic-method – PMC Nov 30 '11 at 09:49
  • T CreateInstance() is inconsistent. I suggest Create (). Also GetAll & fun is redundant either. Jsut make expr == null default. – TomTom Nov 30 '11 at 09:56

2 Answers2

2

Your interface is wrong, it should be:

public interface ICarRepository : IRepository<Car>
{        
}

The error is that you think you're 'using' the Car type, when in fact you're defining a generic parameter named Car. As it isn't constrained to reference types, it can't be used a a parameter to IRepository<>.

jv42
  • 8,521
  • 5
  • 40
  • 64
2

Try changing your interface declaration to

public interface ICarRepository : IRepository<Car> {}

Leaving out the reference to the Car class in the name of the interface. You are inheriting from a generic interface - the inheritance declaration is the only place where you need to declare this class.

Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174