当前位置: 首页 > 工具软件 > ActiveRecord > 使用案例 >

[ActiveRecord] 之二:常用方法

戴高远
2023-12-01
 看下面的例子
[ActiveRecord("Users")]
public class User : ActiveRecordBase
{
    public User() {}

    public User(string name) : this()
    {
        this.name = name;
    }

    private int id;

    [PrimaryKey(PrimaryKeyType.Identity)]
    public int Id
    {
        get { return id; }
        set { id = value; }
    }

    private string name;

    [Property(Unique=true)]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

一般情况下,系统代码生成工具(Castle.ActiveRecord.Generator.exe)会自动生成以下几个静态方法。
public static void DeleteAll()
{
    ActiveRecordBase.DeleteAll(typeof(User));
}
    
public static User[] FindAll()
{
    return ((User[])(ActiveRecordBase.FindAll(typeof(User))));
}
    
public static User Find(int Id)
{
    return ((User)(ActiveRecordBase.FindByPrimaryKey(typeof(User), Id)));
}

很显然这几个方法并不能满足需要,接下来我们补充几个。
public static User Find(string name)
{
    ScalarQuery query = new ScalarQuery(typeof(User), "from User user where user.Name=?", name);
    return ExecuteQuery(query) as User;
}

public static void Delete2()
{
    DeleteAll(typeof(User), "id > 5");
}

public static string GetName(int id)
{
    ScalarQuery query = new ScalarQuery(typeof(User), "select user.Name from User user where user.Id=?", id);
    return ExecuteQuery(query) as string;
}

public static User[] FindAll2(int id)
{
    SimpleQuery query = new SimpleQuery(typeof(User), "from User user where user.Id < ?", id);
    return ExecuteQuery(query) as User[];
}

需要注意的是ActiveRecord(NHibernate)删除记录时,并不是使用单个SQL语句批量删除,而是使用主键依次删除每条记录。晕~~~ 要是删除1000万条记录就得执行1000万条Delete SQL语句。晕~~~~~~~

 类似资料: