NHibernate 中的投影 [英] Projections in NHibernate

查看:19
本文介绍了NHibernate 中的投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在一个实体中有属性 id、用户名、年龄、地址.现在我只想要 id 和用户名,我使用这个代码.

suppose in an entity there are attributes id, username, age, address. Now I just want id and username and I use this code for it.

投影允许返回查询中的实体列表以外的内容.

Projections enable the returning of something other than a list of entities from a query.

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();

我将如何检索值.这些值将在哪个对象中取用.

How will I retrieve the values. In which object will these value be taken.

推荐答案

除非使用结果转换器,否则投影将生成具有投影值的匿名对象列表.这对于数据绑定就足够了.

Unless a result transformer is used, a projection will result in a list of anonymous objects with the projected values. This would be sufficient for databinding.

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

For other uses, you want to set a result transformer which will create objects of a known type. The AliasToBeanTransformer will create an object of the specified type for each row, and set its properties to the row values.

如果你知道结果的类型,你可以使用通用的List()方法.

If you know the type of the results, you can use the generic List<T>() method.

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 查询.

Result transformers can also be used on SQL and HQL queries.

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>();

在这些示例中,Result 类不需要是映射类,并且必须具有选定的属性.

In these examples the the Result class does not need to be a mapped class, and must have the selected properties.

partial class Result
{
    public int Id { get; set; }
    public string Username { get; set; }
}

这篇关于NHibernate 中的投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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