为什么我不能在NHibernate中使用CreateCriteria的泛型? [英] Why can't I use generics with CreateCriteria in NHibernate?

查看:229
本文介绍了为什么我不能在NHibernate中使用CreateCriteria的泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 抽象类BaseRepo< T>抽象类BaseRepo< T> :IRepo< T> 
{
private ISession _session;
$ b $ public Entity GetById< Entity>(int Id)
{
return _session.Get< Entity>(Id);
}

//其他方法
}

我想添加另一个方法来返回一个对象(实体)的所有行。我想做一些事情:

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

但是我收到一个错误消息:


$为了在泛型类型或方法'NHibernate.ISession.CreateCriteria< T>'中使用它作为参数'T',类型'实体'必须是引用类型。 ()'

以下是我的DAL设计供参考:我应该使用泛型来简化我的DAL吗?

解决方案

CreateCriteria 方法需要您使用引用类型 - 为您的DAL方法添加约束:

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

这自然意味着任何实体

我还建议将您的泛型类型参数命名为 TEntity - 实体单独有点令人困惑(因为它完全可以称为实体基类)。


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?

解决方案

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).

这篇关于为什么我不能在NHibernate中使用CreateCriteria的泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆