Skip to content

Quick start

sdrapkin edited this page Jan 6, 2017 · 15 revisions

Install TinyORM From NuGet

Install-Package TinyORM

Basic query

// add "using" statements
using System.Threading.Tasks;
using SecurityDriven.TinyORM; 
// create DbContext instance out of some connection string
var db = DbContext.CreateDbContext(connectionString:
  "Data Source=.\\SQL2012;Initial Catalog=tempdb;Integrated Security=True;Pooling=true;Max Pool Size=3000;");

var rows = await db.QueryAsync("select [Answer] = 2 + 3"); // "rows" is of type IReadOnlyList<dynamic>

// You can use any of these 3 ways to dynamically access the row data:
Console.WriteLine(rows[0].Answer); // 5
Console.WriteLine(rows[0][0]); // 5
Console.WriteLine(rows[0]["Answer"]); // 5

Static-type projection

public class POCO
{
    public int Answer { get; set; }
}
// single static projection:
var poco = (rows[0] as RowStore).ToObject(() => new POCO());
Console.WriteLine(poco.Answer); // 5

// static projection of a list of rows:
var ids = await db.QueryAsync("select [Answer] = object_id from sys.objects;");
var pocoArray = ids.ToObjectArray(() => new POCO());
for (int i = 0; i < pocoArray.Length; ++i) Console.WriteLine(ids[i].Answer);

Parameterization - Anonymous object

var ids1 = await db.QueryAsync(
    "select [Answer] = object_id from sys.objects where object_id between @low and @high;",
    new { @low = 10, @high = 40});

var ids2 = await db.QueryAsync(
    "select [Answer] = object_id from sys.objects where object_id in (@range)",
    new { @range = Enumerable.Range(1, 40) });

// To pass in NULL for value types use Nullable null values:
var emptyResult = await db.QueryAsync(
    "select [Answer] = object_id from sys.objects where object_id = @id",
    new { @id = default(int?) }); // or "@id = (int?)null"

Parameterization - Dictionary

var parameters = new Dictionary<string, object>();
parameters.Add("@low", 10);
parameters.Add("@high", 40);

var ids = await db.QueryAsync(
    "select [Answer] = object_id from sys.objects where object_id between @low and @high;",
    parameters);

Missing or misspelled column names

var rows = await db.QueryAsync("select [Answer] = 2 + 3");
Console.WriteLine(rows[0].Answer is FieldNotFound); // False
Console.WriteLine(rows[0].answer is FieldNotFound); // True

[..unfinished..]

Clone this wiki locally