using Detached.Annotations;
using Detached.Mappers.EntityFramework;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
static async Task Main(string[] args)
Console.WriteLine("- create entity");
using (DetachedDbContext context = new DetachedDbContext())
context.Database.EnsureCreated();
context.Add(new InvoiceType { Id = 1, Name = "A" });
context.Add(new InvoiceType { Id = 2, Name = "B" });
'invoiceType': { 'id': 2 },
await context.MapJsonAsync<Invoice>(json);
await context.SaveChangesAsync();
using (DetachedDbContext context = new DetachedDbContext())
Invoice persisted = await context.Invoices
.Include(i => i.InvoiceType)
Assert(persisted != null, "persisted not null");
Assert(persisted.InvoiceType != null, "invoice type not null");
Assert(persisted.InvoiceType.Name == "B", "invoice type is B");
Assert(persisted.Rows.Count == 2, "row count is 2");
Assert(persisted.Rows.Any(r => r.Description == "prod 1" && r.Quantity == 5), "row values inserted");
Assert(persisted.Rows.Any(r => r.Description == "prod 2" && r.Quantity == 3), "row values inserted");
using (DetachedDbContext context = new DetachedDbContext())
'invoiceType': { 'id': 1 }
await context.MapJsonAsync<Invoice>(json);
await context.SaveChangesAsync();
using (DetachedDbContext context = new DetachedDbContext())
Invoice persisted = await context.Invoices
.Include(i => i.InvoiceType)
Assert(persisted != null, "persisted not null");
Assert(persisted.InvoiceType != null, "invoice type not null");
Assert(persisted.InvoiceType.Name == "A", "invoice type is A");
Assert(persisted.Rows.Count == 2, "row count is 2");
Assert(persisted.Rows.Any(r => r.Description == "prod 1" && r.Quantity == 5), "row values inserted");
Assert(persisted.Rows.Any(r => r.Description == "prod 2" && r.Quantity == 3), "row values inserted");
Console.WriteLine("[test ended]");
static void Assert(bool condition, string label)
Console.WriteLine($"{label}: ok");
Console.WriteLine($"{label}: error!");
public class DetachedDbContext : DbContext
static SqliteConnection _connection;
static ILoggerFactory _loggerFactory;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
_connection = new SqliteConnection($"DataSource=file:{Guid.NewGuid()}?mode=memory&cache=shared");
optionsBuilder.UseSqlite(_connection)
.UseLoggerFactory(_loggerFactory);
public DbSet<Invoice> Invoices { get; set; }
public virtual int Id { get; set; }
public virtual InvoiceType InvoiceType { get; set; }
public virtual List<InvoiceRow> Rows { get; set; }
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int Id { get; set; }
public virtual string Description { get; set; }
public virtual double Quantity { get; set; }
public virtual double Price { get; set; }