ActiveRecordBase.ExecuteQuery(IActiveRecordQuery query) 让我们可以用 hql 执行一些复杂的查询操作。
ExecuteQuery(ew ScalarQuery(typeof(User), "from User u where u.Age > ?", 18));
常用的 Query 对象包有 ScalarQuery 和 SimpleQuery 两种类型,那么他们在使用上有什么不同?
ScalarQuery.cs
public ScalarQuery(Type targetType, string hql, params object[] parameters) : base(targetType)
{
this.hql = hql;
this.parameters = parameters;
}
public override object Execute(ISession session)
{
IQuery query1 = session.CreateQuery(this.hql);
if (this.parameters != null)
{
for (int num1 = 0; num1 < this.parameters.Length; num1++)
{
query1.SetParameter(num1, this.parameters[num1]);
}
}
return query1.UniqueResult();
}
SimpleQuery.cs
public SimpleQuery(Type returnType, string hql, params object[] parameters) :
this(returnType, returnType, hql, parameters)
{
}
public SimpleQuery(Type targetType, Type returnType, string hql, params object[] parameters) :
base(targetType)
{
this.returnType = returnType;
this.hql = hql;
this.parameters = parameters;
}
public override object Execute(ISession session)
{
IQuery query1 = session.CreateQuery(this.hql);
if (this.parameters != null)
{
for (int num1 = 0; num1 < this.parameters.Length; num1++)
{
query1.SetParameter(num1, this.parameters[num1]);
}
}
return base.GetResultsArray(this.returnType, query1.List(), false);
}
通过上面的源码,我们会发现 SimpleQuery 主要用来返回一个同类型(returnType)数组,如:
//1. 返回实体对象数组
User[] users = (User[])User.ExecuteQuery(new SimpleQuery(typeof(User), "from User u where u.Sex = ?", Sex.Male));
//2. 返回单个属性数组
string[] usernames = (String[])User.ExecuteQuery(new SimpleQuery(typeof(User), typeof(string), "select u.Username from User u where u.Sex = ?", Sex.Male));
而 ScalarQuery 除了返回实体对象数组外,主要用来返回单个对象的多个属性。需要注意的是 ScalarQuery 返回的可能是数组也可能是单个数据,因此要在使用前进行判断和类型转换。
//1. 返回实体对象或数组
object result = User.ExecuteQuery(new ScalarQuery(typeof(User), "from User u where u.Sex = ?", Sex.Male));
if (result is Array)
{
User[] users = result as User[];
}
else
{
User user = result as User;
}
//2. 返回单个实体对象的多个属性
Object[] values = (Object[])User.ExecuteQuery(new ScalarQuery(typeof(User), "select u.Username, u.Name from User u where u.Username = ?", "username7"));