【发布时间】:2021-07-05 14:10:58
【问题描述】:
在我的 API 项目中,实体类别如下:
[Key]
public string Id { get; set; }
public string Title { get; set; }
public Category(string id, string title)
还有 Category 是属性的实体产品:
[Key]
public string Id { get; set; }
[Required(ErrorMessage = "Título é obrigatório.")]
[MaxLength(60, ErrorMessage = "Este campo deve conter enre 3 e 60 caracteres.")]
[MinLength(3, ErrorMessage = "Este campo deve conter enre 3 e 60 caracteres.")]
public string Title { get; set; }
[MaxLength(1024, ErrorMessage = "Este campo deve ter no máximo 1024 caracteres")]
public string Description { get; set; }
[Required(ErrorMessage = "Este campo é obrigatório")]
[Range(1, int.MaxValue, ErrorMessage = "O preço deve ser maior que zero")]
public decimal Price { get; set; }
public int AvailableQuantity { get; set; }
[Required(ErrorMessage = "Este campo é obrigatório")]
public string CategoryId { get; set; }
public Category Category { get; set; }
这是 ProductController 中的 Create 方法:
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult<Product>> Create([FromBody] Product model)
{
var category = _context.Categories.AsNoTracking().FirstOrDefault(x => x.Id == model.CategoryId);
if (category == null)
return Ok("Categoria informada não existe");
if (ModelState.IsValid)
{
_product.GenerateId(model);
var product = new Product(model.Id, model.Title, model.Description, model.Price, model.CategoryId, category);
_context.Products.Add(product);
await _context.SaveChangesAsync();
return product;
}
else
{
return BadRequest(ModelState);
}
}
当我尝试创建新产品时,我收到如下错误消息:
System.ArgumentException:已添加具有相同键的项目。钥匙:280CF21D
在 System.Collections.Generic.Dictionary2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary2.Add(TKey 键,TValue 值)
在 Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryTable1.Create(IUpdateEntry entry) at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryStore.ExecuteTransaction(IList1 个条目,IDiagnosticsLogger1 updateLogger) at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryDatabase.SaveChangesAsync(IList1 个条目,CancellationToken cancelToken)
在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at TesteAPI.Controllers.ProductsController.Create(Product model) in C:\Users\tcho3\source\repos\TesteAPI\TesteAPI\Controllers\ProductsController.cs:line 93 at lambda_method56(Closure , Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用程序,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 isCompleted)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed 上下文)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态&下一个,范围&范围,对象&状态,布尔& isCompleted)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- 上一个位置的堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker 调用程序,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 isCompleted)
在 Microsoft.AspNetCore.Mvc.Infrastructure.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 上下文)
在 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
在 Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext,ISwaggerProvider swaggerProvider)
在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)
【问题讨论】:
-
你能发布 _product.GenerateId(model);也请?
-
参见:public void GenerateId(Product product) { product.Id = Guid.NewGuid().ToString().Replace("-", "").ToUpper().Substring(0, 8); }
标签: c# .net entity-framework asp.net-core .net-core