Home > database >  EF Core - null value in column "Id" of relation table violates not-null constraint
EF Core - null value in column "Id" of relation table violates not-null constraint

Time:03-13

I seem to have this error when I insert something into my database table now. It is meant to auto-increment the id when adding a new item, and it has been working for months and I don't remember changing it so no idea why this is happening:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. ---> Npgsql.PostgresException (0x80004005): 23502: null value in column "Id" of relation "VeganItems" violates not-null constraint

DETAIL: Failing row contains (null, new item33, Aa, A, 0, 0, 0, 0, [{"Id":5,"IconCodePoint":63279,"Name":"Condiments"},{"Id":11,"Ic..., {}, GroceryItem, null, null, null, null, null, null, null, null, null, null, 2022-03-13 14:29:40.995771, 2022-03-13 14:29:40.995771, null, KbnrgvYIt5UgTFohyyaSQ1GDIp02). at Npgsql.Internal.NpgsqlConnector.g__ReadMessageLong|213_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage) at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken) at Npgsql.NpgsqlDataReader.NextResult() at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior) at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader() at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) Exception data: Severity: ERROR SqlState: 23502 MessageText: null value in column "Id" of relation "VeganItems" violates not-null constraint Detail: Failing row contains (null, new item33, Aa, A, 0, 0, 0, 0, [{"Id":5,"IconCodePoint":63279,"Name":"Condiments"},{"Id":11,"Ic..., {}, GroceryItem, null, null, null, null, null, null, null, null, null, null, 2022-03-13 14:29:40.995771, 2022-03-13 14:29:40.995771, null, KbnrgvYIt5UgTFohyyaSQ1GDIp02). SchemaName: public TableName: VeganItems ColumnName: Id File: execMain.c Line: 1889 Routine: ExecConstraints --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList1 entries) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple2 t) at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges() at Vepo.DataContext.VepoContext.SaveChanges() in /Users/benjaminfarquhar/dev/vepo_back_end/Vepo.DataContext/VepoContext.cs:line 48 at Vepo.Data.VeganItemEstablishmentsRepository3.Insert(TVeganItemEstablishment entity) in /Users/benjaminfarquhar/dev/vepo_back_end/Vepo.Data/Repositories/VeganItemEstablishments/VeganItemEstablishmentsRepository.cs:line 62 at Vepo.Services.VeganItemEstablishmentsService4._InsertVeganItemEstablishment(TVeganItemEstablishmentDto entity) in /Users/benjaminfarquhar/dev/vepo_back_end/Vepo.Services/VeganItemEstablishments/VeganItemEstablishmentsService.cs:line 240 at Vepo.Services.VeganItemEstablishmentsService4._handleNewVeganItem(TVeganItemEstablishmentDto veganItemEstablishment, ServiceResponse1 _response) in /Users/benjaminfarquhar/dev/vepo_back_end/Vepo.Services/VeganItemEstablishments/VeganItemEstablishmentsService.cs:line 153 at Vepo.Services.VeganItemEstablishmentsService4.AddOrUpdate(TVeganItemEstablishmentDto entity) in /Users/benjaminfarquhar/dev/vepo_back_end/Vepo.Services/VeganItemEstablishments/VeganItemEstablishmentsService.cs:line 104 at Vepo.Web.Controllers.VeganItemEstablishmentsController4.PostVeganItemEstablishment(TVeganItemEstablishmentDto veganItemEstablishment) in /Users/benjaminfarquhar/dev/vepo_back_end/Vepo.Web/Controllers/VeganItemEstablishment/VeganItemEstablishmentsController.cs:line 34 at lambda_method321(Closure , Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) dbug: 03/13/2022 14:29:41.271 CoreEventId.

The code is just:

protected DbSet veganItems;

public async override Task<TVeganItemEstablishment> Insert(
    TVeganItemEstablishment entity)
{
    var toReturnVeganItem = entity.VeganItem;
    var toReturnEstablishment = entity.Establishment;

    var result = veganItems.Add(entity.VeganItem);
    context.SaveChanges();

model builder:

    // Vegan Items

    modelBuilder.Entity<VeganItem>(veganItem =>
    {
        veganItem.HasIndex("CompanyName", "Name", "Discriminator").IsUnique();
        veganItem.HasDiscriminator<string>("Discriminator");
        veganItem.Property(u => u.CreatedDate)
            .HasDefaultValueSql("CURRENT_TIMESTAMP"); 
        veganItem.Property(u => u.UpdatedDate)
            .HasDefaultValueSql("CURRENT_TIMESTAMP"); 
        veganItem.HasKey(e => e.Id);
        veganItem.HasOne(q => q.UpdatedBy)
            .WithMany()
            .HasForeignKey(k => k.UpdatedById);
        veganItem.HasOne(q => q.CreatedBy)
            .WithMany()
            .HasForeignKey(k => k.CreatedById);
        veganItem.Property(e => e.Tags)
            .HasConversion(
                v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
                v => JsonSerializer.Deserialize<List<Option>>(v, (JsonSerializerOptions)null)
            );
    });

entity:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Nest;
using Newtonsoft.Json;
using Vepo.Application;

namespace Vepo.Domain
{
    [Serializable]
    public class VeganItem : CreatedBySomeone
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string CompanyName { get; set; }
        public string Description { get; set; }
        [Required]
        public int IsNotVeganCount { get; set; } = 0;
        [Required]
        public int IsVeganCount { get; set; } = 0;
        [Required]
        public int RatingsCount { get; set; } = 0;
        [Required]
        public int Rating { get; set; }
        public List<Option> Tags { get; set; }
        [MaxLength(10)]
        public List<String> Images { get; set; }
        public string Discriminator { get; set; }
    }

}

using System;
using System.ComponentModel.DataAnnotations;
using AutoMapper;

namespace Vepo.Domain
{
    [Serializable]
    public abstract class DomainEntity<TId> : DomainEntity
    {
        [Key]
        public TId Id { get; set; }
    }

    [Serializable]
    public abstract class DomainEntity 
    {
        public System.DateTime CreatedDate { get; set; }
        public System.DateTime UpdatedDate { get; set; }
    }

    public abstract class CreatedBySomeone : DomainEntity<int>
    {
        public string CreatedById { get; set; }
        public User CreatedBy { get; set; }
        public string UpdatedById { get; set; }
        public User UpdatedBy { get; set; }
    }
}

Edit: it appears that Id is 0, not null:

enter image description here

CodePudding user response:

Your entity configuration does not autoincrement the Id.

Update VeganItem COnfiguration and Add this line in addition to AddKey.

    veganItem.Property(e => e.Id).IsRequired().ValueGeneratedOnAdd();
  • Related