网站首页 博客 C#使用Castle.ActiveRecord操作数据库
1. Visual Studio解决方案目录结构

项目ActiveRecordTest引用的有Castle.ActiveRecord所有dll和项目Models
项目Models引用的有Castle.ActiveRecord中的Castle.ActiveRecord.dll和NHibernate.dll
项目Models是数据表的模型类库,单独放在一个项目中便于管理
2. 应用程序配置文件App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" /> </configSections> <activerecord> <config> <add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" /> <add key="dialect" value="NHibernate.Dialect.MsSql2000Dialect" /> <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" /> <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" /> <add key="connection.connection_string" value="UID=sa;Password=123456;Initial Catalog=student;Data Source=localhost" /> </config> </activerecord> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
3. 建立数据表结构,例如specialty
| 列名 | 数据类型 | 允许Null值 | 说明 |
| id | int | 否 | 标识,主键 |
| type | tinyint | 否 | 类型:1院,2系,3专业 |
| parentid | int | 否 | 父级id |
| name | varchar(100) | 否 | 名称 |
| regtime | datetime | 是 | 创建时间 |
4. 建立数据表模型,例如Specialty.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.ActiveRecord;
namespace Models
{
[ActiveRecord("specialty")]
public class Specialty : ActiveRecordBase<Specialty>
{
[PrimaryKey("id")]
public int id { get; set; }
[Property("type")]
public int type { get; set; }
[Property("parentid")]
public int parentid { get; set; }
[Property("name")]
public string name { get; set; }
[Property("regtime")]
public string regtime { get; set; }
}
}5. 数据库操作方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Framework.Config;
using Models;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.ByteCode.Castle;
using System.Reflection;
namespace ActiveRecordTest
{
public partial class Form1 : Form
{
private static IConfigurationSource source;
public Form1()
{
InitializeComponent();
source = (IConfigurationSource)ConfigurationManager.GetSection("activerecord");
}
//添加记录
private void button1_Click(object sender, EventArgs e)
{
try
{
ActiveRecordStarter.Initialize(source, typeof(Specialty));
Specialty special = new Specialty();
special.type = 3;
special.parentid = 2;
special.name = "计算机科学与技术";
special.regtime = DateTime.Now.ToString();
special.Create();
MessageBox.Show("添加成功");
}
catch (Exception ex)
{
MessageBox.Show("添加失败!" + ex.Message);
}
}
//修改记录
private void button2_Click(object sender, EventArgs e)
{
try
{
ActiveRecordStarter.Initialize(source, typeof(Specialty));
Specialty special = new Specialty();
special = Specialty.Find(3); //获取id=3的记录
special.name = "计算机科学与技术111";
special.u.p.d.a.t.e();
MessageBox.Show("修改成功");
}
catch (Exception ex)
{
MessageBox.Show("修改失败!" + ex.Message);
}
}
//删除记录
private void button3_Click(object sender, EventArgs e)
{
try
{
ActiveRecordStarter.Initialize(source, typeof(Specialty));
Specialty special = new Specialty();
special.id = 3; //删除id=3的记录
special.d.e.l.e.t.e();
MessageBox.Show("删除成功");
}
catch (Exception ex)
{
MessageBox.Show("删除失败!" + ex.Message);
}
}
//读取记录
private void button4_Click(object sender, EventArgs e)
{
ActiveRecordStarter.Initialize(source, typeof(Specialty));
DetachedCriteria query = DetachedCriteria.For(typeof(Specialty));
query.Add(Property.ForName("id").Gt(1)); //查询条件id>1
query.AddOrder(Order.Desc("id")); //排序方式id desc
var result = Specialty.FindAll(query);
foreach (Specialty onespecial in result)
{
textBox1.Text += onespecial.id +", "+ onespecial.name +", "+ onespecial.regtime +"\r\n";
}
}
//批量修改
private void button5_Click(object sender, EventArgs e)
{
ActiveRecordStarter.Initialize(source, typeof(Specialty));
ISessionFactoryHolder sessionHolder = ActiveRecordMediator.GetSessionFactoryHolder();
ISession session = sessionHolder.CreateSession(typeof(Specialty));
try
{
System.Data.IDbCommand command = session.Connection.CreateCommand();
command.CommandText = "u.p.d.a.t.e special set name=name+'123' w.h.e.r.e id<4"; //执行sql语句
command.ExecuteNonQuery();
textBox1.Text = "修改成功";
}
catch (Exception ex)
{
throw ex;
}
sessionHolder.ReleaseSession(session);
}
//批量删除
private void button6_Click(object sender, EventArgs e)
{
ActiveRecordStarter.Initialize(source, typeof(Specialty));
ActiveRecordMediator.d.e.l.e.t.eAll(typeof(Specialty), "id>2"); //批量删除id>2的记录
}
}
}