當我現在在我的資料庫表中插入一些東西時,我似乎遇到了這個錯誤。它旨在在添加新專案時自動增加 id,它已經作業了幾個月,我不記得更改它,所以不知道為什么會這樣:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:錯誤:執行請求時發生未處理的例外。
Microsoft.EntityFrameworkCore.DbUpdateException:保存物體更改時出錯。有關詳細資訊,請參閱內部例外。---> Npgsql.PostgresException(0x80004005):23502:關系“VeganItems”的“Id”列中的空值違反非空約束
詳細資訊:失敗行包含 (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). 在 Npgsql.Internal.NpgsqlConnector.g__ReadMessageLong|213_0(NpgsqlConnector 連接器, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReading BooleanPrependedMessage) at Npgsql.Npgsql,DataReader isNextResult(Boolean.Npgsql,DataReader isNextResult(Boolean.Npgsql,DataReaderisNextResult) Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior 行為,布爾異步,CancellationToken cancelToken)在 Npgsql 的 Npgsql.NpgsqlDataReader.NextResult() 的 CancellationToken 取消令牌)。Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior 行為)處 Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior 行為)處的 NpgsqlCommand.ExecuteReader(CommandBehavior 行為,布爾異步,CancellationToken cancelToken)
在 System.Data.Common.DbCommand.ExecuteReader() 在 Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject) 在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection 連接) 例外資料:嚴重性:錯誤 SqlState:23502 MessageText :關系“VeganItems”的“Id”列中的空值違反非空約束詳細資訊:失敗行包含(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,空,2022-03-13 14:29:40.995771,2022-03-13 14:29:40.995771,空,KbnrgvYIt5UgTFohyyaSQ1GDIp02)。架構名:公共表名:VeganItems ColumnName:Id 檔案:execMain.c 行:1889 例程:ExecConstraints --- 內部例外堆疊跟蹤結束---在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) 在 Microsoft.EntityFrameworkCore.Update.Internal。 BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList1 個條目)在 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) 在 Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) 在 Microsoft。 EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) 在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) 在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges() 在 Vepo.DataContext.VepoContext.SaveChanges() 在 /Users/benjaminfarquhar /dev/vepo_back_end/Vepo.DataContext/VepoContext.cs:第 48 行,位于 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) 在 /Users/benjaminfarquhar/dev/ve Services/VeganItemEstablishments/VeganItemEstablishmentsService.cs:Vepo.Services.VeganItemEstablishmentsService 的第 153 行4.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:第 34 行 lambda_method321(Closure , Object) at Microsoft.AspMethodNetCore.Mvc.Infrastructure.Autor.A Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker 呼叫程式,ValueTask`1 actionResultValueTask) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker 的 .Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 執行器,物件控制器,Object[] arguments) Microsoft.AspNetCore.Mvc.Infrastructure 的 .g__Awaited|10_0(ControllerActionInvoker 呼叫程式,Task lastTask,State next,Scope 范圍,Object state,Boolean isCompleted)。Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() 的 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 的 ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) --- End來自先前位置的堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure 的 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker 呼叫程式,Task lastTask,State next,Scope 范圍,Object state,Boolean isCompleted) .ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure。ResourceInvoker.InvokeFilterPipelineAsync() --- 從上一個位置結束堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure 的 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍) .ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍)在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端點端點,任務 requestTask,ILogger 記錄器)在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext背景關系)在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 背景關系)在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 背景關系)dbug:03/13/2022 14:29:41.271 CoreEventId。InvokeFilterPipelineAsync() --- 從上一個位置結束堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker 的 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍) .g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍)在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端點端點,任務 requestTask,ILogger 記錄器)在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 背景關系)在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) dbug:03/13/2022 14:29:41.271 CoreEventId。InvokeFilterPipelineAsync() --- 從上一個位置結束堆疊跟蹤 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker 的 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍) .g__Awaited|17_0(ResourceInvoker 呼叫程式,任務任務,IDisposable 范圍)在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端點端點,任務 requestTask,ILogger 記錄器)在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 背景關系)在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) dbug:03/13/2022 14:29:41.271 CoreEventId。
代碼只是:
受保護的 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();
模型構建器:
// 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)
);
});
物體:
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; }
}
}
編輯:似乎 Id 為 0,而不是 null:

uj5u.com熱心網友回復:
您的物體配置不會自動增加 ID。
更新 VeganItem 配置并在 AddKey 之外添加此行。
veganItem.Property(e => e.Id).IsRequired().ValueGeneratedOnAdd();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442251.html
上一篇:過濾值的VBA計算
