Пример программы:
Код: Выделить всё
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
();
sc.AddDbContext(options =>
options
.UseSqlite("Data Source=:memory:")
.EnableDetailedErrors()
.UseLoggerFactory(loggerFactory)
);
var services = sc.BuildServiceProvider();
using var scope = services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService();
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 options) : DbContext(options)
{
public DbSet 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)
{
}
}
Код: Выделить всё
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'.
Подробнее здесь: https://stackoverflow.com/questions/785 ... base-table