Skip to content
Auswöger Matthias edited this page Apr 9, 2021 · 4 revisions

Inserting and Querying a single Customer record

Objective

In the following tutorial we will create an example that is initializing a SQLite database, inserts a Customer into it and query it afterwards.

Steps

Create application

Create a console application with the following commands:

dotnet new console -n "ObjectStoreDemo"
cd .\ObjectStoreDemo\

Add Nuget package

Add the latest version of an ObjectStore library nuget package, the SQLite version in this case:

dotnet add package ObjectStore.SQLite

Using statements

Add using statements to the program.cs file:

using System.Linq;
using ObjectStore;
using ObjectStore.OrMapping;
using ObjectStore.Sqlite;

Entity class

Add a Customer entity class:

[Table("Customer")]
public abstract class Customer
{
    [Mapping(FieldName="Id"), IsPrimaryKey]
    public abstract int Id { get; }

    [Mapping(FieldName = "Name")]
    public abstract string Name { get; set; }

    [Mapping(FieldName = "Contact")]
    public abstract string Contact { get; set; }

    [Mapping(FieldName = "Address")]
    public abstract string Address { get; set; }

    [Mapping(FieldName = "City")]
    public abstract string City { get; set; }

    [Mapping(FieldName = "PostalCode")]
    public abstract string PostalCode { get; set; }

    [Mapping(FieldName = "Country")]
    public abstract string Country { get; set; }
}

Setup method

Add the following method to do the setup:

public static void Setup()
{
	RelationalObjectStore relationalObjectStore = 
		new RelationalObjectStore("Data Source=Database.db", DataBaseProvider.Instance)
			.Register<Customer>();
	ObjectStoreManager.DefaultObjectStore.RegisterObjectProvider(relationalObjectStore);
	relationalObjectStore.InitializeDatabase();
}

this needs to be done once at startup before it is used.

Main method

Change the main method to call the Setup method and use the ORMapper:

public static void Main()
{
	Setup();
	Customer customer = ObjectStoreManager.DefaultObjectStore.CreateObject<Customer>();
	customer.FirstName = "John";
	customer.LastName = "Doe";
	customer.Address = "123 Main St";
	customer.City = "Anytown";
	customer.PostalCode = "12345-6789";
	customer.Country = "United States";
	ObjectStoreManager.DefaultObjectStore.GetQueryable<Customer>().Save();
	IQueryable<Customer> queryable = ObjectStoreManager.DefaultObjectStore.GetQueryable<Customer>();
}

Full example

Checkout the full example here.