Skip to content

Instantly share code, notes, and snippets.

@gistlyn
Last active September 9, 2021 13:37
Show Gist options
  • Save gistlyn/a62b1e7a8da57c7d1fda95b3da5303eb to your computer and use it in GitHub Desktop.
Save gistlyn/a62b1e7a8da57c7d1fda95b3da5303eb to your computer and use it in GitHub Desktop.
Simple OrmLite CRUD demo
using System;
using System.Collections.Generic;
using ServiceStack;
using ServiceStack.Text;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.DataAnnotations;
public class User
{
public long Id { get; set; }
[Index]
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public override string ToString() => Name;
}
var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
var db = dbFactory.Open(); //Open ADO.NET DB Connection
db.DropAndCreateTable<User>(); //DROP (if exist) and CREATE Table from User POCO
db.Insert( //INSERT multiple Users by params
new User { Id = 1, Name = "A", CreatedDate = DateTime.Now },
new User { Id = 2, Name = "B", CreatedDate = DateTime.Now },
new User { Id = 3, Name = "C", CreatedDate = DateTime.Now },
new User { Id = 4, Name = "C", CreatedDate = DateTime.Now });
var rowsC = db.Select<User>(x => x.Name == "C"); //SELECT by typed expression
$"No of 'C' Rows: {rowsC.Count}, Ids:".Print(); //= 2
rowsC.ConvertAll(x => x.Id).PrintDump(); //= 3,4
db.Delete<User>(x => x.Name == "C"); //DELETE by typed expression
var remainingC = db.Select<User>("Name= @name", new { name="C" }); //Custom SQL
$"No of 'C' Rows: {remainingC.Count}".Print(); //= 0
var rowsLeft = db.Select<User>();
$"Rows Left: {rowsLeft.Count}".Print(); //= 2
rowsLeft.PrintDump(); //= A,B
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.Memory" version="4.5.4" targetFramework="net45" />
<package id="ServiceStack.Text" version="5.10.0" targetFramework="net45" />
<package id="ServiceStack.Client" version="5.10.0" targetFramework="net45" />
<package id="ServiceStack.Common" version="5.10.0" targetFramework="net45" />
<package id="ServiceStack.Interfaces" version="5.10.0" targetFramework="net45" />
<package id="ServiceStack.OrmLite" version="5.10.0" targetFramework="net45" />
<package id="ServiceStack.OrmLite.Sqlite.Windows" version="5.10.0" targetFramework="net45" />
</packages>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment