otal
8/27/2016 - 8:00 AM

ormlite complex save

ormlite complex save

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ServiceStack.Text" version="4.5.0" targetFramework="net45" />
  <package id="ServiceStack.Interfaces" version="4.5.0" targetFramework="net45" />
  <package id="ServiceStack.Common" version="4.5.0" targetFramework="net45" />
  <package id="ServiceStack.OrmLite" version="4.5.0" targetFramework="net45" />
  <package id="ServiceStack.OrmLite.Sqlite.Mono" version="4.5.0" targetFramework="net45" />
</packages>
using System;
using System.Collections.Generic;
using ServiceStack;
using ServiceStack.Text;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.DataAnnotations;
using System.Data;
using System.Linq;

public class Customer
{
    [AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }

    [Reference] // Save in CustomerAddress table
    public CustomerAddress PrimaryAddress { get; set; }

    [Reference] // Save in Order table
    public List<Order> Orders { get; set; }
}

public class CustomerAddress
{
    [AutoIncrement]
    public int Id { get; set; }
    public int CustomerId { get; set; } //`{Parent}Id` convention to refer to Customer
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}

public class Order
{
    [AutoIncrement]
    public int Id { get; set; }
    public int CustomerId { get; set; } //`{Parent}Id` convention to refer to Customer
    public string LineItem { get; set; }
    public int Qty { get; set; }
    public decimal Cost { get; set; }
}

var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
var db = dbFactory.Open();     //Open ADO.NET DB Connection

db.DropAndCreateTable<Customer>(); //DROP (if exist) and CREATE Table from User POCO
db.DropAndCreateTable<Order>(); 
db.DropAndCreateTable<CustomerAddress>(); 

var customer =  new Customer {
    Name = "Customer 1",
    PrimaryAddress = new CustomerAddress {
        AddressLine1 = "1 Australia Street",
        Country = "Australia"
    },
    Orders = new[] {
        new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
        new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
    }.ToList(),
};

db.Save(customer, references:true);

var customers = db.LoadSelect<Customer>(x => x.Name == "Customer 1");
customers.PrintDump();