通过第一篇的介绍,相信大家也对Db4o有一定的了解,接下来就详细说一下有关查询的话题。
Db4o原生支持3中查询模式:
下面给出一个职工类
/// <summary> /// 职工 /// </summary> class Employee { /// <summary> /// 姓名 /// </summary> string _name; public string Name { set { _name = value; } get { return _name; } } /// <summary> /// 职位 /// </summary> public Position Position { get; set; } public override string ToString() { return string.Format("姓名:{0},职位:{1}",this.Name,this.Position.PositionName); } } /// <summary> /// 职位 /// </summary> class Position { /// <summary> /// 职称 /// </summary> public string PositionName { get; set; } }
填充测试数据
static List<Employee> GetEmployee() { List<Employee> _Employees = new List<Employee>(); Employee _Employee = new Employee { Name = "Sunth", Position = new Position { PositionName = "CEO" } }; _Employees.Add(_Employee); _Employee = new Employee { Name = "Jerry", Position = new Position { PositionName = "CTO" } }; _Employees.Add(_Employee); _Employee = new Employee { Name = "Tom", Position = new Position { PositionName = "COO" } }; _Employees.Add(_Employee); return _Employees; }
static void Main(string[] args) { string DbPath = "Pilot.yap"; if (File.Exists(DbPath)) File.Delete(DbPath); using (IObjectContainer Container = Db4oEmbedded.OpenFile(DbPath)) { //对数据库进行初始化,并存入测试数据 var Query = GetEmployee(); Query.ForEach ( (a) => { Container.Store(a); } ); //查询一个叫做Sunth的职工 Employee _Employee = new Employee(); _Employee.Name = "Sunth"; IObjectSet Result = Container.QueryByExample(_Employee); //打印结果 PrintResult(Result); } Console.ReadKey(); }
static void Main(string[] args) { string DbPath = "Pilot.yap"; if (File.Exists(DbPath)) File.Delete(DbPath); using (IObjectContainer Container = Db4oEmbedded.OpenFile(DbPath)) { //对数据库进行初始化,并存入测试数据 var Query = GetEmployee(); Query.ForEach ( (a) => { Container.Store(a); } ); //查询一个叫做Sunth的职工 Employee _Employee = new Employee(); var Result = Container.Query<Employee> ( delegate(Employee employee) { return employee.Name == "Sunth"; } ); //打印结果 PrintResult(Result); } Console.ReadKey(); }
static void Main(string[] args) { string DbPath = "Pilot.yap"; if (File.Exists(DbPath)) File.Delete(DbPath); using (IObjectContainer Container = Db4oEmbedded.OpenFile(DbPath)) { //对数据库进行初始化,并存入测试数据 var Query = GetEmployee(); Query.ForEach ( (a) => { Container.Store(a); } ); //查询一个叫做Sunth的职工 IQuery _IQuery = Container.Query(); //强制约束Employee类型 _IQuery.Constrain(typeof(Employee)); //注意此“_name”为字段名称,非属性名称 _IQuery.Descend("_name").Constrain("Sunth"); //执行查询 IObjectSet Result = _IQuery.Execute(); //打印结果 PrintResult(Result); } Console.ReadKey(); }