我使用NHibernate的最后一个版本在我的MVC项目使用NHibernate的使用ResultTransformer
我想做出一个对象类型名称“人”的查询,但人有许多特性。在我的一个问题中,我最好不要拥有大部分这些属性。 这里是人:
public partial class Person
{
virtual public User User { get; set; }
virtual public string FirstName { get; set; }
virtual public string LastName { get; set; }
virtual public int Gender { get; set; }
virtual public Contact Contact { get; set; }
virtual public BirthCertificate PersonBirthCertificate { get; set; }
}
在查询我只想名字和人的姓氏。
所以我决定用使用ResultTransformer和实现它是这样的:
public class PersonResultTransformer : IResultTransformer
{
private Type result;
private PropertyInfo[] properties;
#region IResultTransformer Members
public IList TransformList(IList collection)
{
return collection;
}
public PersonResultTransformer (Type result, params string[] names)
{
this.result = result;
List<PropertyInfo> props = new List<PropertyInfo>();
foreach (string name in names)
{
props.Add(result.GetProperty(name));
}
properties = props.ToArray();
}
public object TransformTuple(object[] tuple, string[] aliases)
{
object instance = Activator.CreateInstance(result);
for (int i = 0; i < tuple.Length; i++)
{
var t = properties[i].Name;
var value = tuple[i].GetType().GetProperty(t).GetValue(tuple[i], null);
instance.GetType().GetProperty(t).SetValue(instance, value, null);
}
return instance;
}
#endregion
}
,并为获得要我要与LINQ查询:
var person = Repository<Person>.Find(p => p.LastName.Equals("Nadal")
, new PersonResultTransformer (typeof(Person), "FirstName", "LastName"));
////////////////
public IQueryable<T> Find(Expression<Func<T, bool>> expression, IResultTransformer transformer)
{
return Session.CreateCriteria<T>().SetResultTransformer(transformer).List<T>()
.AsQueryable().Where(expression);
}
,可以吗?它可以更定制?我是否正确使用它?
看来,它有一个很大的问题:它得到所有人的姓氏和名字,然后从中选择,那些姓氏=“纳达尔”,而且性能也不好
没有使用创建标准,而只是使用查找扩展库仑我做到了吗? – Adrakadabra 2012-01-02 13:24:41
我怎么能用linq来做到休眠? – Adrakadabra 2012-01-02 13:41:46
Linq到Nhibernate是Nhibernate源自(我认为)3.2以来的一部分,因此它已经可以使用了。在StackOverflow上有很多关于它的帖子,你可以看看[这里](http://nhforge.org/blogs/nhibernate/archive/2009/12/16/using-the-new-linq-to-nh-提供商和迁移 - 从最老one.aspx)。 – 2012-01-03 08:41:48