Skip to content

Instantly share code, notes, and snippets.

@gistlyn
Last active November 10, 2020 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gistlyn/6aca5ffeca1046e3d8d5b0429b548ee8 to your computer and use it in GitHub Desktop.
Save gistlyn/6aca5ffeca1046e3d8d5b0429b548ee8 to your computer and use it in GitHub Desktop.
Create Tables with Complex Types
using System.Collections.Generic;
using ServiceStack.Text;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.DataAnnotations;
var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
var db = dbFactory.Open();
public class ArtistWithBlobTracks
{
public int Id { get; set; }
public string Name { get; set; }
public List<Track> Tracks { get; set; } //By default Complex Types are blobbed with the containing record
}
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
[Reference] public List<Track> Tracks { get; set; } //Complex Type References are persisted in own table
}
public class Track
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Album { get; set; }
public int ArtistId { get; set; } // Implicit Reference Id
}
db.CreateTable<ArtistWithBlobTracks>();
db.CreateTable<Artist>();
db.CreateTable<Track>();
db.Insert(new ArtistWithBlobTracks {
Id = 1, Name = "Faith No More",
Tracks = new List<Track> {
new Track { Name = "Everythings Ruined", Album = "Angel Dust" },
new Track { Name = "Ashes to Ashes", Album = "Album of the Year" } }
});
var artistWithBlobTracks = db.SingleById<ArtistWithBlobTracks>(1);
$"Artist with blobbed Tracks: {artistWithBlobTracks.Dump()}".Print();
$"Blob Tracks Count: {db.Count<Track>()}".Print();
db.Save(new Artist {
Id = 1, Name = "Faith No More",
Tracks = new List<Track> {
new Track { Name = "Everythings Ruined", Album = "Angel Dust" },
new Track { Name = "Ashes to Ashes", Album = "Album of the Year" } }
}, references: true);
var artistWithRefTracks = db.LoadSingleById<Artist>(1);
$"Artist with referenced Tracks: {artistWithRefTracks.Dump()}".Print();
$"Referenced Tracks Count: {db.Count<Track>()}".Print();
<?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