We are using EF Core with Sqlite to test the database of our app. However we are unable to store any entities in the DB tables.
Sample program:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ConsoleApp5;
class Program
{
static void Main(string[] args)
{
var sc = new ServiceCollection();
ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
ILogger logger = loggerFactory.CreateLogger<Program>();
sc.AddDbContext<Context>(options =>
options
.UseSqlite("Data Source=:memory:")
.EnableDetailedErrors()
.UseLoggerFactory(loggerFactory)
);
var services = sc.BuildServiceProvider();
using var scope = services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<Context>();
dbContext.Database.EnsureCreated();
try
{
var myA = new A();
dbContext.As.Add(myA);
dbContext.SaveChanges();
var x = dbContext.As.Find(myA.Id);
Console.WriteLine( myA.Id);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
public class Context(DbContextOptions<Context> options) : DbContext(options)
{
public DbSet<A> As { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
A.OnModelCreating(modelBuilder);
}
};
public abstract class Entity
{
public string Id { get; set; } = Guid.NewGuid().ToString();
}
public class A : Entity
{
internal static void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
this results in the following logging, table is created, but insert fails:
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (12ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "type" = 'table' AND "rootpage" IS NOT NULL;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "As" (
"Id" TEXT NOT NULL CONSTRAINT "PK_As" PRIMARY KEY
);
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (3ms) [Parameters=[@p0='?' (Size = 36)], CommandType='Text', CommandTimeout='30']
INSERT INTO "As" ("Id")
VALUES (@p0);
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'ConsoleApp5.Context'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: As'.
What are we doing wrong?