[ActiveRecord] 之八:Queries

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



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值