我想使用this method从我的数据库中动态获取数据。正如该主题中所解释的,我应该为我的nhibernate配置添加扩展。
有人可以说,请问如何添加该扩展程序?
提前致谢。
public static class NhTransformers
{
public static readonly IResultTransformer ExpandoObject;
static NhTransformers()
{
ExpandoObject = new ExpandoObjectResultSetTransformer();
}
private class ExpandoObjectResultSetTransformer : IResultTransformer
{
public IList TransformList(IList collection)
{
return collection;
}
public object TransformTuple(object[] tuple, string[] aliases)
{
var expando = new ExpandoObject();
var dictionary = (IDictionary<string, object>)expando;
for (int i = 0; i < tuple.Length; i++)
{
string alias = aliases[i];
if (alias != null)
{
dictionary[alias] = tuple[i];
}
}
return expando;
}
}
}
public static class NHibernateExtensions
{
public static IList<dynamic> DynamicList(this IQuery query)
{
return query.SetResultTransformer(NhTransformers.ExpandoObject)
.List<dynamic>();
}
}
-----------------------------------
USE CASE
-----------------------------------
var results = this.session.CreateSQLQuery("select Id, Title, Body from [Posts]")
.DynamicList(); // Secret sauce!
// results are now dynamic!
Console.WriteLine(results[0].Id);
Console.WriteLine(results[0].Name);
// rock on!
答案 0 :(得分:0)
最后,我只创建了NhTransformers类并且确实喜欢这个;
var query1 = " select * from mySQLView";
var result1 = this.session.CreateSQLQuery(query1).SetResultTransformer(NhTransformers.ExpandoObject)
.List<dynamic>();
foreach (var obj in result1)
{
// some stuff...
}