首先要引入必要的名字空间:
using System.IO;
using Db4objects.Db4o;
打开数据库:
IObjectContainer db = Db4oFactory.OpenFile(Util.YapFileName);//文件名Util.YapFileName,没找到文件的话会自动创建
存储一个对象:
Pilot pilot1 = new Pilot("Michael Schumacher", 100);
db.Set(pilot1);//执行存储,数据库中可以没有指定的Pilot类型,当成容器往里面装就行
按类型读取对象:
IObjectSet result = db.Get(typeof(Pilot));
foreach (object o in result)
{
Pilot p = (Pilot)o;
}
按属性读取对象:
Pilot proto = new Pilot(null, 100);//找到分数为一百的车手,null为前一个属性string的默认值
IObjectSet result = db.Get(proto);
更新对象:
IObjectSet result = db.Get(new Pilot("Michael Schumacher", 0));
Pilot found = (Pilot)result.Next();
found.AddPoints(11);
db.Set(found);
删除对象:
IObjectSet result = db.Get(new Pilot("Michael Schumacher", 0));
Pilot found = (Pilot)result.Next();
db.Delete(found);
附:
public class Pilot
{
string _name;
int _points;
public Pilot(string name, int points)
{
_name = name;
_points = points;
}
public string Name
{
get
{
return _name;
}
}
public int Points
{
get
{
return _points;
}
}
public void AddPoints(int points)
{
_points += points;
}
override public string ToString()
{
return string.Format("{0}/{1}", _name, _points);
}
}