0

In my Base repo I have this code which works fine:

abstract class BaseRepo <T> : IRepo <T>
{
    private ISession _session;

    public Entity GetById<Entity>(int Id)
    {
        return _session.Get<Entity>(Id);
    }

    // other methods
}

I want to add another method to return all rows for an object (entity). I want to do something like:

    public IList<Entity> GetAll<Entity>()
    {
        return _session.CreateCriteria<Entity>().List<Entity>;
    }

but I get an error saying:

The type 'Entity' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NHibernate.ISession.CreateCriteria<T>()'

Here's my DAL design for reference: Should I use generics to simplify my DAL?

Community
  • 1
  • 1
Mark Allison
  • 6,838
  • 33
  • 102
  • 151

1 Answers1

4

CreateCriteria method requires you to use reference types - add constraint on your DAL method:

public IList<Entity> GetAll<Entity>()
     where Entity : class
{
    return _session.CreateCriteria<Entity>().List<Entity>();
}

This naturally implies that any Entity type you pass to this method must be a reference type.

I also suggest naming your generic type parameter TEntity - Entity alone is a bit confusing (as it's perfectly fine name for say, entity base class).

k.m
  • 30,794
  • 10
  • 62
  • 86
  • Thanks that builds OK, but when I exercise it in my unit test I get this error: `M:Test.RepoTest.CanGetAllAccounts failed: Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object.` – Mark Allison Jan 12 '12 at 18:07
  • Is your `_session` set to an actual instance? How `CanGetAllAcounts` test method looks like? Do you use any test setup method? There can be multiple reasons for NRE, without more code it's really hard to tell. – k.m Jan 12 '12 at 18:13
  • Oh no i feel so dumb. I had forgotten to put my [Test] attribute on my test. Once I had done that it worked. Doh! – Mark Allison Jan 12 '12 at 18:23