Orders表Name列非空约束违反问题求助
Orders表Name列非空约束冲突问题
错误详情
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 "Name" of relation "Orders" violates not-null constraint DETAIL: Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information. at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|234_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage) at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken) Exception data: Severity: ERROR SqlState: 23502 MessageText: null value in column "Name" of relation "Orders" violates not-null constraint Detail: Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information. SchemaName: public TableName: Orders ColumnName: Name File: execMain.c Line: 1968 Routine: ExecConstraints --- 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.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken) at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at RentAPI.Persistence.Contexts.RentAPIDbContext.SaveChangesAsync(CancellationToken cancellationToken) in C:\Users\Admin\Desktop\ahmet-rent\RentAPI\Infrastructure\RentAPI.Persistence\Contexts\RentAPIDbContext.cs:line 35 at RentAPI.Persistence.Repositories.WriteRepository`1.SaveAsync() in C:\Users\Admin\Desktop\ahmet-rent\RentAPI\Infrastructure\RentAPI.Persistence\Repositories\WriteRepository.cs:line 55 at RentAPI.API.Controllers.ProductsController.Get() in C:\Users\Admin\Desktop\ahmet-rent\RentAPI\Presentation\RentAPI.API\Controllers\ProductsController.cs:line 39 at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>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>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) HEADERS ======= Accept: */* Host: localhost:7035 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64 Accept-Encoding: gzip, deflate, br, zsdch Accept-Language: tr,en;q=0.9,en-GB;q=0.8,en-US;q=0.7 Referer: https://localhost:7035/swagger/index.html sec-ch-ua: "Chromium";v="112", "Microsoft Edge";v="112", "Not:A-Brand";v="99" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" sec-fetch-site: same-origin sec-fetch-mode: cors sec-fetch-dest: empty
相关代码
Customer实体(Customer.cs)
using RentAPI.Domain.Entities.Common; using System.Collections.Generic; namespace RentAPI.Domain.Entities { public class Customer : BaseEntity { public string Name { get; set; } public ICollection<Order> Orders { get; set; } } }
Order实体(Order.cs)
using RentAPI.Domain.Entities.Common; using System.Collections.Generic; namespace RentAPI.Domain.Entities { public class Order : BaseEntity { public Guid CustomerId { get; set; } public string Description { get; set; } public string Address { get; set; } public ICollection<Product> Products { get; set; } public Customer Customer { get; set; } } }
ProductsController控制器(ProductsController.cs)
using Microsoft.AspNetCore.Mvc; using RentAPI.Application.Repositories; using RentAPI.Domain.Entities; namespace RentAPI.API.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { readonly private IProductWriteRepository _productWriteRepository; readonly private IProductReadRepository _productReadRepository; readonly private IOrderWriteRepository _orderWriteRepository; readonly private ICustomerWriteRepository _customerWriteRepository; public ProductsController( IProductWriteRepository productWriteRepository, IProductReadRepository productReadRepository, IOrderWriteRepository orderWriteRepository, ICustomerWriteRepository customerWriteRepository) { _productWriteRepository = productWriteRepository; _productReadRepository = productReadRepository; _orderWriteRepository = orderWriteRepository; _customerWriteRepository = customerWriteRepository; } [HttpGet] public async Task Get() { var customerId = Guid.NewGuid(); await _customerWriteRepository.AddAsync(new() { Id = customerId, Name = "Ahmet" }); await _orderWriteRepository.AddAsync(new() { Description = "bla bla bla", Address = "Antalya Korkuteli", CustomerId = customerId}); await _orderWriteRepository.AddAsync(new() { Description = "bla bla bla 2", Address = "Antalya Alanya", CustomerId = customerId}); await _orderWriteRepository.SaveAsync(); } } }
问题背景
此前因数据库问题删除了数据库和迁移记录,重新创建迁移并应用后,执行添加Customer及关联Order的操作时触发上述错误。Orders表存在Name列且带有非空约束,但Order实体中并未定义该属性,尝试给Order实体添加Name属性后问题依旧。
解决方案建议
- 检查迁移文件正确性:查看重新生成的迁移文件,确认是否错误地给Orders表添加了Name列。如果有,手动删除该列的创建代码,再重新执行迁移应用命令。
- 清理数据库结构:直接检查PostgreSQL数据库中的Orders表,若存在多余的Name列,手动删除该列;或者直接删除数据库,重新创建后应用正确的迁移。
- 排查EF Core配置:检查DbContext中的实体配置,确认是否通过Fluent API或数据注解错误地给Order实体映射了Name属性,导致生成多余的表列。
- 重新生成迁移:删除现有的所有迁移文件,确保Order实体没有Name属性,然后重新执行
Add-Migration生成正确的迁移脚本,再执行Update-Database同步到数据库。
内容的提问来源于stack exchange,提问作者prawlercode
相关产品推荐
相关产品推荐

