为什么我不能在NHibernate中使用CreateCriteria的泛型? [英] Why can't I use generics with CreateCriteria in NHibernate?
问题描述
抽象类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>();
}
这自然意味着任何 我还建议将您的泛型类型参数命名为 In my Base repo I have this code which works fine: I want to add another method to return all rows for an object (entity). I want to do something like: but I get an error saying: Here's my DAL design for reference: Should I use generics to simplify my DAL? This naturally implies that any I also suggest naming your generic type parameter 这篇关于为什么我不能在NHibernate中使用CreateCriteria的泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!实体$ c
TEntity
- 实体
单独有点令人困惑(因为它完全可以称为实体基类)。abstract class BaseRepo <T> : IRepo <T>
{
private ISession _session;
public Entity GetById<Entity>(int Id)
{
return _session.Get<Entity>(Id);
}
// other methods
}
public IList<Entity> GetAll<Entity>()
{
return _session.CreateCriteria<Entity>().List<Entity>;
}
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>()'
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
type you pass to this method must be a reference type.TEntity
- Entity
alone is a bit confusing (as it's perfectly fine name for say, entity base class).