Timur2342
@Timur2342

По какой причине появляеться SqliteException: SQLite Error 19: 'NOT NULL constraint failed?

Логи:
spoiler

fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (6ms) [Parameters=[@p0='?' (DbType = Guid), @p1='?' (Size = 3), @p2='?' (Size = 17), @p3='?' (DbType = Boolean), @p4='?' (Size = 6), @p5='?' (Size = 60), @p6='?'], CommandType='Text', CommandTimeout='30']
INSERT INTO "Users" ("id", "creditCardId", "email", "emailConfirmed", "name", "passwordHash", "profilePicturePath")
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6);
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20002]
Closing connection to database 'main' on server 'C:\xxx\megadb.db'.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20003]
Closed connection to database 'main' on server 'megadb.db' (2ms).
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'Market.DbContexts.ApplicationDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'NOT NULL constraint failed: Users.profilePicturePath'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'NOT NULL constraint failed: Users.profilePicturePath'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)

Внимание на OnModelCreating. DbContextOptions нужен лишь для того чтобы вызваьть UseSqlite().
DbContext:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
        if (Database.CanConnect() is false)
            Database.EnsureCreated();
    }
    public DbSet<UserEntity> Users => Set<UserEntity>();
    public DbSet<CreaditCardEntity> CreaditCards => Set<CreaditCardEntity>();
    public DbSet<PurchaseEntity> Purchases => Set<PurchaseEntity>();

    public DbSet<SalesmanEntity> Salesmans => Set<SalesmanEntity>();
    public DbSet<ProductEntity> Products => Set<ProductEntity>();
    public DbSet<ReviewEntity> Reviews => Set<ReviewEntity>();
    public DbSet<DeliveryServiceEntitycs> DeliveryServices => Set<DeliveryServiceEntitycs>();
    public DbSet<TagEntity> Tags => Set<TagEntity>();
    public DbSet<FileEntity> Files => Set<FileEntity>();
    public DbSet<ProductSpecificationEntity> ProductSpecifications => Set<ProductSpecificationEntity>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){}
    protected override void OnModelCreating(ModelBuilder builder){}
}


Внимание на свойство ProfilePicturePath.
UserEntity:

[PrimaryKey(nameof(Id))]
public class UserEntity
{
    public UserEntity()
    {
        Id = Guid.NewGuid();
    }
    [Column("id"), Required]
    public Guid Id { get; set; }

    [Column("name"), Required]
    public string Name { get; set; }

    [Column("email"), Required]
    public string Email { get; set; }
    [Column("emailConfirmed")]
    public bool EmailConfirmed { get; set; }

    [Column("passwordHash"), Required]
    public string PasswordHash { get; set; }

    public List<PurchaseEntity> Purchases { get; set; }

    [Column("profilePicturePath")]
    public string ProfilePicturePath { get; set; }
    [Column("creditCardId"), Required]
    public string CreditCardId { get; set; }
    
    [ForeignKey("CreditCardId")]
    public CreaditCardEntity CreditCardEntity { get; set; }
}

По какой причине могла появиться ошибка? ProfilePicturePath нигде пока что не добавляю, да и вобще не юзаю его. И самое главное, у него нету ведь [Required] или IsRequired, по идеи он может быть null.
  • Вопрос задан
  • 77 просмотров
Решения вопроса 1
@mvv-rus
Настоящий админ AD и ненастоящий программист
Исправьте вот здесь:
[Column("profilePicturePath")]
    public string? ProfilePicturePath { get; set; }

Пояснение. В документации по EF Core написано:
Если включены ссылочные типы, допускающие значение NULL, свойства будут настроены на основе nullability C# для типа .NET: string? будут настроены как необязательные, но string будут настроены по мере необходимости.

В современных шаблонах проектов nullability включена по умолчанию, так что ваш тип свойства string EF понимает как то, что соответствующая колонка записи должна иметь ограничение NOT NULL. А потому вам следует использовать в качестве типа свойства string? .
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы