using Detached.Annotations;
using Detached.Mappers.EntityFramework;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
static void 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 = new { Id = 1 },
new { Id = 1, Description = "prod 1", Quantity = 5, Price = 25 },
new { Id = 2, Description = "prod 2", Quantity = 3, Price = 100 }
using (DetachedDbContext context = new DetachedDbContext())
Invoice persisted = context.Invoices.Where(i => i.Id == 1).Include(i => i.InvoiceType).Include(i => i.Rows).FirstOrDefault();
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("- update entity");
using (DetachedDbContext context = new DetachedDbContext())
InvoiceType = new { Id = 2 },
new { Id = 1, Description = "prod 1", Quantity = 5, Price = 25 },
new { Id = 2, Description = "prod 2 edited", Quantity = 8, Price = 100 }
using (DetachedDbContext context = new DetachedDbContext())
Invoice edited = context.Invoices.Where(i => i.Id == 1).Include(i => i.InvoiceType).Include(i => i.Rows).FirstOrDefault();
Assert(edited != null, "persisted not null");
Assert(edited.InvoiceType != null, "invoice type not null");
Assert(edited.InvoiceType.Name == "B", "invoice updated to B");
Assert(edited.Rows.Count == 2, "row count is 2");
Assert(edited.Rows.Any(r => r.Description == "prod 2 edited" && r.Quantity == 8), "row values updated");
Console.WriteLine("[test ended]");
static void Assert(bool condition, string label)
Console.WriteLine($"{label}: ok");
Console.WriteLine($"{label}: error!");
class DetachedDbContext : DbContext
static SqliteConnection _connection;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
_connection = new SqliteConnection($"DataSource=file:{Guid.NewGuid()}?mode=memory&cache=shared");
optionsBuilder.UseSqlite(_connection)
public DbSet<Invoice> Invoices { get; set; }
public int Id { get; set; }
public InvoiceType InvoiceType { get; set; }
public List<InvoiceRow> Rows { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int Id { get; set; }
public string Description { get; set; }
public double Quantity { get; set; }
public double Price { get; set; }