1、项目中引用Castle.ActiveRecord中所需要的dll,包括
Castle.ActiveRecord.dll
.Castle.Core.dll
.Castle.DynamicProxy.dll
.Iesi.Collections.dll
.log4net.dll
.NHibernate.dll
2、创建数据库Castel,此处使用的是Sql2008
3、创建表Users
CREATE TABLE [dbo].[Users](
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [varchar](10) NULL,
[Password] [varchar](50) NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
4、创建配置文件DbConfig.xml,放置Castle.ActiveRecord的配置信息,配置文件要设置成始终复制
<?xml version="1.0" encoding="utf-8" ?>
<activerecord>
<config>
<add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="connection.connection_string" value="server=.;database=Castle;uid=sa;pwd=123456"/>
<add key="show_sql" value="true"/>
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
</config>
</activerecord>
5、创建实体对象User
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.ActiveRecord;
using System.Collections;
namespace Castle
{
[ActiveRecord("Users")]
public class User : ActiveRecordBase
{
[PrimaryKey]
public int id { set; get; }
[Property("UserName")]
public string UserName { set; get; }
[Property("Password")]
public string Password { set; get; }
public static void DeleteAll()
{
DeleteAll(typeof(User));
}
public static IList FindAll()
{
return (IList)FindAll(typeof(User));
}
public static User Find(int id)
{
return (User)FindByPrimaryKey(typeof(User), id);
}
public static bool Exists(int id) {
return Exists(typeof(User),id);
}
}
}
6、初始化Castle.ActiveRecord,初始化的对象可自由增加
IConfigurationSource source = new XmlConfigurationSource(
Environment.CurrentDirectory + @"\DbConfig.xml");
ActiveRecordStarter.Initialize(source, typeof(User));
7、使用
//查询所有
private void InitList(User us)
{
this.dataGrid1.DataContext = User.FindAll();
}
代码上传一份,http://download.youkuaiyun.com/download/cky151/7581229 供大家参考