OrmLite SQL Server Example

December 24th, 2014 | Posted by Robert Curlette in OrmLite | ServiceStack - (0 Comments)

ORMLite is a great example of a framework that does one thing and does it well. If we’re looking for a efficient and solid way to get and put data in a DB within .Net (or Mono) then the ServiceStack ORMLite micro-orm is a great choice. It was created by Demis Bellot. One of the great things about ServiceStack is the high level of support from Demis and you can find many of his answers on StackExchange. In this post I will explain how to quickly setup a connection to SQL Server and add / query 1 row. If you have used ORMLite before this article might not shed any new light into the ORMLite scenario for you. Note that the current version of OrmLite (v4) is paid software and uses a quota system for small projects and evaluations. The license allows a developer to use it for a DB of up to 10 tables for free.

Getting Started

1. Create a new .Net Console Application
2. Add a NuGet reference to OrmLite.SqlServer library

Prepare SQL Server

1. Create a new Database User (if needed) for your new DB.
2. Create a new Database (ORMLite does not do this for you)
3. Give the DB User permissions to the new DB
4. Create the connection string: “Server=Dev2011;Database=ItemInfoDb;User Id=MyNewDbUser;Password=S3cr3tPw;”

Write the code

The below code creates an instance of a POCO, and then saves it to the DB. Note the AutoIncrement data attribute. This creates our PK.

For more in-depth information I highly recommend the official ServiceStack documentation. and ORMLite example here.

I wanted to create a simple app to store data using the elegant OrmList from ServiceStack.  During this process I found a couple of things that cost me some time and I wanted to share these with you.  In this article I will walk through creating a small and simple ServiceStack OrmLite example.  It should take around 5 minutes to complete the example.

Please see the excellent OrmLite official docs for more examples.

Update Jan 6, 2013:  Code samples updated with the great feedback in the comments from Demis Bellot.

Step 1:  Create a Console App and Reference OrmLite.SQLite

– Create a Console app named OrmLiteExample

– Add the OrmLite references from NuGet (http://www.nuget.org).  Right-click on the References in the Solution Explorer, Manage NuGet Packages, Online, OrmLite.  Or, from the Package Manager Console (View, Other Windows, Package Manager Console) type ‘Install-Package ServiceStack.OrmLite.Sqlite32’.

Step 2:  Create the DTO (aka Model)

This is the nicest part of working with ServiceStack.  Everything is DTO and Model driven – no config files to create and the code is simple and concise.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.DataAnnotations;

namespace OrmLiteExample
    class Note
        [AutoIncrement] // Creates Auto primary key
        public int Id { get; set; }

        public string SchemaUri { get; set; }
        public string NoteText { get; set; }
        public DateTime? LastUpdated { get; set; }
        public string UpdatedBy { get; set; }

Step 3:  In program.cs, add the Using statements

using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;

The using statement ServiceStack.OrmLite.Sqlite will throw an exception if you build now.

Fix:  With NuGet, download and install ServiceStack.OrmLite.Sqlite32 package. Also, go to the properties of your project and make sure the target framework is set to .NET framework 4.  Solved!

Step 4:  Add the connection strings for SqLite

Thanks to the nice Unit Tests in the ServiceStack project I was able to use their example.

public static string SqliteMemoryDb = ":memory:";
// Updated per comment form Jonas.  First connection string below causes an app pool restart!  Use MapHostAbsolutePath instead!
//public static string SqliteFileDb = "~/App_Data/db.sqlite".MapAbsolutePath();  
public static string SqliteFileDb = "~/App_Data/db.sqlite".MapHostAbsolutePath();
Problem:  The MapAbsolutePath is not found.
Fix: Include the missing library:

using ServiceStack.Common.Utils;

Step 5:  Create the connection

//Using Sqlite DB- improved
var dbFactory = new OrmLiteConnectionFactory(
                SqliteFileDb, false, SqliteDialect.Provider);

// Wrap all code in using statement to not forget about using db.Close()
using (var db = dbFactory.Open()) {

Step 6: Create the Table



Step 7:  Insert a record

Note:  This is different than the excellent online examples.  I received a warning message to use the Connection instead of the Command object.

// Insert
	new Note {
		SchemaUri = "tcm:0-0-0",
		NoteText = "Hello world 5",
		LastUpdated = new DateTime(2013, 1, 5),
		UpdatedBy = "RC" });

Step 8:  Read the data

 // Read
var notes = db.Where<Note>(new { SchemaUri = "tcm:0-0-0" });
foreach (Note note in notes)
	Console.WriteLine("note id=" + note.Id + "noteText=" + note.NoteText);

Full Code