在DB4O中按类型查询

Fai*_* S. 4 .net c# db4o function argument-passing

如何将类类型传递给C#中的函数?

当我进入db4o和C#时,我在阅读教程后编写了以下函数:

    public static void PrintAllPilots("CLASS HERE", string pathToDb)
    {
        IObjectContainer db = Db4oFactory.OpenFile(pathToDb);
        IObjectSet result = db.QueryByExample(typeof("CLASS HERE"));
        db.Close();
        ListResult(result);
    }
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 11

有两种方法.第一种是明确使用Type类型.

public static void PrintAllPilots(Type type, string pathToDb)
{
  ...
  IObjectSet result = db.QueryByExample(type);
}

PrintAllPilots(typeof(SomeType),somePath);
Run Code Online (Sandbox Code Playgroud)

第二是使用泛型

public static void PrintAllPilots<T>(string pathToDb)
{
  ...
  IObjectSet result = db.QueryByExample(typeof(T));
}

PrintAllPilots<SomeType>(somePath);
Run Code Online (Sandbox Code Playgroud)


Jud*_*ngo 5

Jon,Jared和yshuditelu给出的答案使用了很大程度上未使用的DB4o查询机制的查询示例,并且可能在将来被弃用.

查询DB4O for .NET的首选方法是本机查询和LINQ.

// Query for all Pilots using DB4O native query:
var result = db.Query<Pilot>();
Run Code Online (Sandbox Code Playgroud)

或者使用Linq-to-DB4O:

// Query for all Pilots using LINQ
var result = from Pilot p in db
             select p;
Run Code Online (Sandbox Code Playgroud)

这两项工作都为您提供了编译时的类型(例如Pilot).如果您在编译时不知道类型,则可以改为使用DB4O SODA查询:

var query = db.Query();
query.Constrain(someObj.GetType());
var results = query.Execute();
Run Code Online (Sandbox Code Playgroud)

编辑为什么使用LINQ而不是SODA,Query-by-Example(QBE)或Native Query(NQ)?因为LINQ使得查询表达式非常自然.例如,以下是您如何查询名为迈克尔的飞行员:

var michaelPilots = from Pilot p in db
                    where p.Name == "Michael"
                    select p;
Run Code Online (Sandbox Code Playgroud)

LINQ是可组合的,这意味着你可以做这样的事情:

var first20MichaelPilots = michaelPilots.Take(20);
Run Code Online (Sandbox Code Playgroud)

当您迭代结果时,您仍然可以在DB4O中执行高效查询.在SODA或QBE或NQ中做同样的事情是最难的.