如何解决我正在添加一个实体类别作为另一个实体产品的属性 System.ArgumentException:已添加具有相同键的项目
在我的 API 项目中,有实体 Category 如下:
[Key]
public string Id { get; set; }
public string Title { get; set; }
public Category(string id,string title)
以及类别是属性的实体产品:
[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.Dictionary
2.Add(TKey key,TValue value)
在 Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryTable1.Create(IUpdateEntry entry) at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryStore.ExecuteTransaction(IList
1 个条目,IDiagnosticslogger1 updateLogger) at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryDatabase.SaveChangesAsync(IList
1 个条目,CancellationToken 取消令牌)
在 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 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,ValueTask
1 actionResultValueTask)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用者,任务上一个任务,下一个状态,作用域范围,对象状态,布尔值已完成)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next,Scope& scope,Object& state,Boolean& isCompleted)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterasync()
--- 从上一个位置开始的堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker,Task lastTask,State next,Scope scope,Object state,Boolean isCompleted)
在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 调用者,任务任务,Idisposable 范围)
在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint,Task requestTask,ILogger logger)
在 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 context)
解决方法
修复模型
public class Category
{
[Key]
public string Id { get; set; }
public string Title { get; set; }
.....
public virtual ICollection<Product> Products { get; set}
}
您也不需要 Product 的特殊构造函数,因为您使用 Product 作为模型
修正你的行为
public async Task<ActionResult<Product>> Create([FromBody] Product model)
{
//---------- I don't think that you really need this
var category = _context.Categories.AsNoTracking().FirstOrDefault(x => x.Id == model.CategoryId);
if (category == null) return Ok("Categoria informada não existe");
//---------
//would be enough
if (model.category == 0) return Ok("Categoria informada não existe");
if (ModelState.IsValid)
{
_product.GenerateId(model);
_context.Products.Add(model;
await _context.SaveChangesAsync();
return model;
}
else
{
.....
}
}
,
是的,因为该类别已存在于数据库中,因此与该产品相关的类别您只需在创建产品时传递 CategoryId
,如下所示:
var product = new Product(model.Id,model.Title,model.Description,model.Price,model.CategoryId);
无需传递 category
对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。