using System.Threading.Tasks;
using Detached.Mappers.EntityFramework;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
public static async Task Main()
using (TestDbContext dbContext = new TestDbContext())
await dbContext.Database.EnsureCreatedAsync();
InvoiceType invoiceType = new InvoiceType
dbContext.Add(invoiceType);
await dbContext.SaveChangesAsync();
using (TestDbContext dbContext = new TestDbContext())
Invoice invoice = new Invoice
InvoiceType = new InvoiceType { Id = 1 }
dbContext.Entry(invoice).State = EntityState.Added;
dbContext.Entry(invoice.InvoiceType).State = EntityState.Unchanged;
await dbContext.SaveChangesAsync();
using (TestDbContext dbContext = new TestDbContext())
Invoice invoice = new Invoice
InvoiceType = await dbContext.FindAsync<InvoiceType>(1)
await dbContext.SaveChangesAsync();
using (TestDbContext dbContext = new TestDbContext())
var invoice = await dbContext.Invoices.Include(i => i.InvoiceType).FirstOrDefaultAsync();
await dbContext.Invoices.Where(i => i.InvoiceType.Id == 1).FirstOrDefaultAsync();
Console.WriteLine($"Associated invoice type is: '{invoice.InvoiceType.Name}'");
class TestDbContext : DbContext
static SqliteConnection _connection;
_connection = new SqliteConnection($"DataSource=file:{Guid.NewGuid()}?mode=memory&cache=shared");
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlite(_connection).UseMapping();
public DbSet<Invoice> Invoices { get; set; }
public int Id { get; set; }
public string Subject { get; set; }
public DateTime InvoiceDate { get; set; }
public DateTime DueDate { get; set; }
public InvoiceType InvoiceType { get; set; }
public int Id { get; set; }
public string Name { get; set; }