English 中文(简体)
NHibernate 中的投影
原标题:Projections in NHibernate

假设实体中有属性id、username、age和address。现在我只想要id和username,所以我使用了这个代码。

投影可以使查询返回除实体列表以外的其他内容。

var proj = Projections.ProjectionList()
    .Add(Projections.Property("Id"), "Id")
    .Add(Projections.Property("Username"), "Username");

var list2 = DetachedCriteria.For<User>()
    .Add(Expression.Eq("Username", "lachlan"))
    .GetExecutableCriteria( sessionFactory.GetCurrentSession())
    .SetProjection( proj )
    .List();

我将如何取回这些值?这些值将被取出到哪个对象中?

最佳回答

除非使用结果转换器,否则投影将导致一个匿名对象列表,其中包含投影的值。这对于数据绑定是足够的。

对于其他用途,您需要设置一个结果转换器,该转换器将创建已知类型的对象。 AliasToBeanTransformer 将为每行创建指定类型的对象,并将其属性设置为行值。

如果您知道结果的类型,您可以使用通用的List<T>()方法。

var proj = Projections.ProjectionList()
    .Add(Projections.Property("Id"), "Id")
    .Add(Projections.Property("Username"), "Username");

var list2 = DetachedCriteria.For<User>()
    .Add(Expression.Eq("Username", "lachlan"))
    .GetExecutableCriteria( sessionFactory.GetCurrentSession())
    .SetProjection( proj )
    .SetResultTransformer(Transformers.AliasToBean(typeof(Result)))
    .List<Result>();

结果转换器也可以用于SQL和HQL查询。

list2 = Session.CreateSQLQuery("select Id, Username from user_table")
    .SetResultTransformer(Transformers.AliasToBean(typeof(Result)))
    .List<Result>();

list2 = Session.CreateQuery("select Id, Username from User")
    .SetResultTransformer(Transformers.AliasToBean(typeof(Result)))
    .List<Result>();

在这些例子中,结果类不需要是映射类,并且必须具有所选的属性。

partial class Result
{
    public int Id { get; set; }
    public string Username { get; set; }
}
问题回答

暂无回答




相关问题
nHibernate one-to-many inserts but doesnt update

Instead of getting into code, I have a simple question. Default behavior for a simple one-to-many is that it inserts the child record then updates the foreign key column with the parent key. Has ...

How Do I copy an existing nhibernate object as a new object?

I a persisted NHibernate object that I would like to repersist as a new entity. How do I get NHibernate to save this object as if it was a new? I am thinking I might create a session interceptor to ...

join across databases with nhibernate

I am trying to join two tables that reside in two different databases. Every time, I try to join I get the following error: An association from the table xxx refers to an unmapped class. If the ...

WPF - MVVM - NHibernate Validation

Im facing a bit of an issue when trying to validate a decimal property on domain object which is bound to a textbox on the view through the viewmodel. I am using NHibernate to decorate my property on ...

NHibernate Search in a List using ICriteria

I have my class X : public class ClassX { public virtual IList<ClassY> ListY { get; set; } ... } My ClassX mapping (using Fluent) ... HasMany<ClassX>(x => x.ListY ) ....

热门标签