【发布时间】:2020-09-16 19:26:03
【问题描述】:
我在使用延迟加载和virtual 时遇到问题,但是使用它时会产生以下错误
违反PRIMARY KEY约束不能在对象中插入重复键
我该如何解决?
这些是我的课程:
public class Producto
{
[Key]
public Guid ProductoId { get; set; }
public Guid InquilinoId { get; set; }
public string Nombre { get; set; }
public decimal Precio_Publico { get; set; }
public string Detalle_producto { get; set; }
public DateTime? Fecha_publicacion { get; set; }
public bool Activo { get; set; }
public string Img_Producto { get; set; }
public string CodigoBarras { get; set; }
public virtual Concepto VigenciaPrecio { get; set; }
public virtual ICollection<Precio> Precios { get; set; }
public bool Es_Almacenable { get; set; }
public int Dias_de_Garantia { get; set; }
public bool Es_Importado { get; set; }
public virtual List<Categoria> Categoria { get; set; } = new List<Categoria>();
public virtual Impuesto Impuesto { get; set; }
public virtual Precio Precio { get; set; }
}
public class Categoria
{
public Guid CategoriaId { get; set; }
public string Nombre { get; set; }
public virtual Producto Producto { get; set; }
}
[HttpPost]
public async Task<ActionResult<Guid>> Post(Producto producto)
{
var user = await userManager.GetUserAsync(HttpContext.User);
var usercontodo = context.Users.Where(x => x.Id == user.Id).Include(x => x.InquilinoActual).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(producto.Img_Producto))
{
var imgProducto = Convert.FromBase64String(producto.Img_Producto);
producto.Img_Producto = await almacenadorDeArchivos.GuardarArchivo(imgProducto, "jpg", "productos");
}
producto.InquilinoId = usercontodo.InquilinoActual.ClienteId;
context.Add(producto);
await context.SaveChangesAsync();
return producto.ProductoId;
}
这是categorias的表格:
这是表productos:
这是错误:
错误:
Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。
Microsoft.Data.SqlClient.SqlException (0x80131904):违反 主键约束“PK_Categorias”。无法插入重复键 对象'dbo.Categorias'。重复键值为 (1737b24b-93a4-4ad9-4d8b-08d85a75ca8e)
【问题讨论】:
-
将错误发布为文本,而不是图片。
标签: c# entity-framework blazor