Type query in DB4O

How to pass class type to function in C #?

As I get into db4o and C #, I read the following function after reading the tutorials:

public static void PrintAllPilots("CLASS HERE", string pathToDb) { IObjectContainer db = Db4oFactory.OpenFile(pathToDb); IObjectSet result = db.QueryByExample(typeof("CLASS HERE")); db.Close(); ListResult(result); } 
+4
source share
4 answers

There are two ways. The first is to explicitly use the type of the type.

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

The second is the use of generics

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

The answers provided by John, Jared, and the ISU use the query after example, which is a largely unused DB4o query mechanism, and could potentially be deprecated in the future.

The preferred DB4O query methods for .NET are native queries and LINQ.

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

Or, alternatively, using Linq-to-DB4O:

 // Query for all Pilots using LINQ var result = from Pilot p in db select p; 

Both of these provided you with a type (e.g. Pilot) at compile time. If you don't know the type at compile time, you can use the DB4O SODA query instead:

 var query = db.Query(); query.Constrain(someObj.GetType()); var results = query.Execute(); 

edit Why use LINQ instead of SODA, Query-by-Example (QBE) or Native Query (NQ)? Because LINQ makes it very natural to execute query expressions. For example, here, as you request pilots named Michael:

 var michaelPilots = from Pilot p in db where p.Name == "Michael" select p; 

And LINQ is composite, that is, you can do things like this:

 var first20MichaelPilots = michaelPilots.Take(20); 

And you still get an efficient query executed in DB4O when you iterate over the results. Doing the same in SODA or QBE or NQ is ugly at best.

+5
source

I think this is what you want:

 public static void PrintAllPilots(Type classType, string pathToDb) { IObjectContainer db = Db4oFactory.OpenFile(pathToDb); IObjectSet result = db.QueryByExample(classType); db.Close(); ListResult(result); } 
+1
source

You can do it manually using Type :

 public static void PrintAllPilots(Type type, string pathToDb) 

Or you can use generics to type output:

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

Source: https://habr.com/ru/post/1286571/


All Articles