Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the C # open source lightweight object database NDatabase

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to understand C# open source lightweight object database NDatabase, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Today, I introduce NDatabase, an open source lightweight object database under .NET. I spent a day looking at the documentation and some examples. I think it is necessary to organize some things into Chinese documents, which is also convenient for everyone. Originally intended to transform a previous small project, as an example. Helplessly, there is not enough time, but also busy looking for a job. So if you see for yourself, this database is still very useful in some ways. The following totals are translated according to the official documents, slightly removed and modified, and summarized some of the features and features of the database. And then wrote out the key points. A simple addition, deletion and search is changed to the example of the back door. The level of translation is limited, please give us some advice:

1. Preface

NDatabase is an easy-to-use .NET object database. To avoid the overhead of a relational database, try using NDatabase. NDatabase is a new generation of object-oriented database: a native .NET database persistence layer. Its main features are:

Simple: NDatabase is very simple and easy to learn to use; it API is simple and does not need to learn any database mapping technology; does not need to map between objects and storage persistence layers; NDatabase stores objects in the simplest way; does not need to install and manage.

Small: the NDatabase runtime is smaller than 300Kb, and when deploying the program, it is easy to integrate into .NET applications.

Secure and robust: NDatabase supports ACID transactions to ensure data integrity. Even in the case of a hardware failure, all commit work is applied to the database and automatically executed the next time it starts.

Single database file: NDatabase uses a single file to store all data, including metadata, objects, indexes, etc.

Productivity: NDatabase uses very little code for data persistence and no mapping is required. As a result, developers can focus on the implementation of business logic instead of wasting time in the data persistence layer.

Getting started with 2.NDatabase

2.1 basic Settings

All database engine settings in NDatabase are in the OdbConfiguration class. For example, the settings for BTree Validation and BTree index degree are in this class, and the settings for opening the log are also in this class. NDatabase provides a default implementation of the log class: ConsoleLogger, which can be set using the EnableConsoleLogger method in the OdbConfiguration class. After you have implemented the custom log class, you also need to register the RegisterLogger method before you can use it.

OdbConfiguration.RegisterLogger (new Log4NetLogger ())

2.2 use index

Use the IndexManagerFor method of the IOdb interface to add an index to a specified type, such as:

Using (var odb = OdbFactory.Open ("index1.ndb")) {var fields = new [] {"Name"}; odb.IndexManagerFor () .AddUniqueIndexOn ("nameIndex", fields); odb.IndexManagerFor () .AddIndexOn ("nameIndex", new [] {"Result"});}

2.3 use transactions

NDatabase can use transactions to ensure data integrity (ACID: atomicity, consistency, isolation, persistence). When a NDatabase is opened, a session is automatically created containing a special current transaction object that manages all current data and data operations.

2.4 in-memory database mode

NDatabase can load all the data in the database directly into memory, directly using the OpenInMemory of the OdbFactory method.

2.5 about triggers

To add a trigger, first create a class that implements the Trigger interface (), which has four available types (InsertTrigger,UpdateTrigger,SelectTrigger,DeleteTrigger). Such as:

Public class MyTrigger: InsertTrigger {public override bool BeforeInsert (object obj) {return true;} public override void AfterInsert (object obj, OID oid) {}}

During use, after you open the database, you need to register the trigger before you can use:

Var mage = new Mage ("Merlin", 3.3,3.4); var myTrigger = new MyTrigger (); using (var odb = OdbFactory.Open ("inserting_trigger.db")) {odb.TriggerManagerFor () .AddInsertTrigger (myTrigger); odb.Store (mage);}

2.6 extend the database schema

The definition of types may change during the life cycle of the database, NDatabase provides a refactoring management interface, you can extend the database schema, you can use IRefactorManager to rename type and field names, and to add and delete fields. Such as the following code:

Using (var odb = OdbFactory.Open ("Refactoring.odb")) {var refactorManager = odb.GetRefactorManager (); refactorManager.RenameField (typeof (User), "age", "_ age"); refactorManager.RenameField (typeof (User), "name", "_ name");}

2.7 Custom Log Interface

The configuration of logs is mentioned in section 2.1. You can customize the log classes and use them after registration, as shown below:

Public class Log4NetLogger: ILogger {private static readonly ILog Log = LogManager.GetLogger (typeof (ILogger)); # region Implementation of ILogger public void Warning (string message) {Log.Warn (message);} public void Debug (string message) {Log.Debug (message);} public void Info (string message) {Log.Info (message);} public void Error (string message) {Log.Error (message)

2.8 exception handling

NDatabase uses internal exception handling types to handle errors. Here are the exception types in NDatabase:

BTreeException

BTreeNodeValidationException

DuplicatedKeyException

CorruptedDatabaseException

LinqQueryException

2.9 non-persistent attributes

If there are some attributes that you don't want to save to the database, you can use the [NonPersistent] attribute.

3. Several examples of practical use

Of course, there must be an entity class before use, and the entity class of the example is the simplest, so there are some places that will not be written out here.

3.12 examples of saving objects

Let's start with the simple one:

Var sport = new Sport ("volley-ball"); using (var odb = OdbFactory.Open (TutorialDb5MinName)) / / Open database odb.Store (sport)

Let's look at the complicated ones:

View Code var volleyball = new Sport ("volley-ball"); var player1 = new Player ("julia", DateTime.Now, volleyball); var player2 = new Player ("magdalena", DateTime.Now, volleyball); var player3 = new Player ("jacek", DateTime.Now, volleyball); var player4 = new Player ("michal", DateTime.Now, volleyball); var team1 = new Team ("Krakow"); var team2 = new Team ("Skawina"); team1.AddPlayer (player1); team1.AddPlayer (player2) Team2.AddPlayer (player3); team2.AddPlayer (player4); var game = new Game (DateTime.Now, volleyball, team1, team2); using (var odb = OdbFactory.Open (TutorialDb5MinName)) odb.Store (game)

3.2 take a look at a few simple query examples

The simplest, notes are avoided. They are all relatively simple.

Using (var odb = OdbFactory.Open (TutorialDb5MinName)) {var query = odb.Query (); query.Descend ("Name"). Constrain ("julia"). Equal (); var players = query.Execute (); Console.WriteLine ("\ nStep 3 (Soda): Players with name julia"); foreach (var player in players) Console.WriteLine ("\ t {0}", player); Assert.That (players, Has.Count.EqualTo (1)) }

Take a look at this, LINQ query method:

Using (var odb = OdbFactory.Open (TutorialDb5MinName)) {var players = from player in odb.AsQueryable () where player.Name.Equals ("julia") select player; Console.WriteLine ("\ nStep 3 (Linq): Players with name julia"); foreach (var player in players) Console.WriteLine ("\ t {0}", player); Assert.That (players.Count (), Is.EqualTo (1));}

That's all for simple examples.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report