简体   繁体   中英

Generic function to return list of objects using ISession's CreateCritieria function in nHibernate

I could able to create a list of objects by doing like this:

using (var session = sessionFactory.OpenSession()) {              
    ICriteria criteria = session.CreateCriteria<Foo>();
    IList<Foo> Foo = criteria.List<Foo>();
}

where Foo is my class.

I wish to write a generic function to return list of object depending on the input Type as shown below:

public IList<T> GetObjList <T> (T obj)
{
    IList<T> list;
    try {
        var sessionFactory = CreateSessionFactory();
        if (sessionFactory == null)
            return null;
        using (var session = sessionFactory.OpenSession()) {
            ICriteria criteria = session.CreateCriteria<T>(); //Error
            list = criteria.List<T>();
        }
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message);
        return null;
    }
    return list;
}

I'm getting the following compiler error in the line ICriteria criteria = session.CreateCriteria()

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

Please help me to solve this.

Generic type parameters can be further constrained to limit what can be provided as such parameter. What your error message says, is that NHibernate.ISession.CreateCriteria<T>() requires its type parameter to be constrained to reference type . Since your method doesn't define any constraint at all, C# compiler has no clue whether T is a valid type parameter for CreateCriteria<T> .

If we take a closer look at NHibernate source code, we indeed can notice that ISession.CreateCriteria<T> is declared as follows:

public ICriteria CreateCriteria<T>() where T : class

As a result, you need the same constraint on your method in order for type parameter passed to it to play nicely with CreateCriteria call. Simply change it to:

public IList<T> GetObjList<T>(T obj)
    where T : class
{
    /* ... */
}

try

public IList<T> GetObjList <T> (T obj) where T : class
{
    // body doesn't change
}

This restricts the type parameter 'T' to be a 'class' - this means that this method will not accept a value type as 'T'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM