问题描述
在我的基本仓库中,我有下面的代码可以正常工作:
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>()'
以下是我的DAL设计供参考:我应该使用泛型来简化我的DAL?
Here's my DAL design for reference: Should I use generics to simplify my DAL?
推荐答案
CreateCriteria
方法要求您使用引用类型-在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>();
}
这自然意味着您传递给此方法的任何 Entity
类型都必须是引用类型.
This naturally implies that any Entity
type you pass to this method must be a reference type.
我还建议仅命名通用类型参数 TEntity
- Entity
有点令人困惑(因为这是实体基类的完美称呼).
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一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!