c# - SqlException:当 IDENTITY_INSERT 设置为 OFF ASP.NET Core 2.1 时,无法在表“类别”中插入标识列的显式值
问题描述
在我的数据库中插入新产品时,我收到以下 SQL 错误消息:
形式:
错误 SQL:
我一直在寻找有关它的信息,这是一个 SQL 错误,可以从 Entity Framework 修复,但我没有得到好的结果
我所涉及的模型如下...
产品.CS:
public class Producto : IEntity
{
public int Id { get; set; }
[Display(Name = "Nombre")]
[MaxLength(50, ErrorMessage = "El campo {0} solo puede contener {1} caracteres de largo.")]
[Required]
public string Name { get; set; }
[Display(Name = "Descripción")]
[MaxLength(150, ErrorMessage = "El campo {0} solo puede contener {1} caracteres de largo.")]
[Required]
public string Description { get; set; }
[Display(Name = "Precio")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Price { get; set; }
[Display(Name = "Imagen")]
public string ImageUrl { get; set; }
public User User { get; set; }
public Category Category { get; set; }
}
类别.CS:
public class Category : IEntity
{
public int Id { get; set; }
[Display(Name = "Nombre Categoría")]
[Required (ErrorMessage = "El campo categoría es obligatorio.")]
[MaxLength(30, ErrorMessage = "el campo {0} solo puede contener {1} caracteres de largo.")]
public string Name { get; set; }
}
IEntity.CS:
public interface IEntity
{
int Id { get; set; }
}
附上我的产品控制器的 POST 操作..
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ProductoViewModel view)
{
if (ModelState.IsValid)
{
var path = string.Empty;
if (view.ImageFile != null && view.ImageFile.Length > 0)
{
var guid = Guid.NewGuid().ToString();
var file = $"{guid}.jpg";
path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\Productos", file);
using (var stream = new FileStream(path, FileMode.Create))
{
await view.ImageFile.CopyToAsync(stream);
}
path = $"~/images/Productos/{file}";
}
//TRANSFORMO EL PRODUCTO PRODUCTOVIEWMODEL A PRODUCTO
var producto = this.ToProducto(view, path);
//USUARIO CREADOR
producto.User = await userHelper.GetUserByEmailAsync(User.Identity.Name);
//CATEGORIA DEL PRODUCTO
producto.Category = await categoryRepository.GetByIdAsync(view.CategoryId);
await productoRepository.CreateAsync(producto);
//FALTA VALIDAR QUE DEVUELVE (TRUE OR FALSE)
return RedirectToAction(nameof(Index));
}
return View(view);
}
private Producto ToProducto(ProductoViewModel view, string path)
{
return new Producto
{
Id = view.Id,
ImageUrl = path,
IsAvailabe = view.IsAvailabe,
LastSale = view.LastSale,
Name = view.Name,
Description = view.Description,
Price = view.Price,
Stock = view.Stock,
User = view.User,
Category = view.Category
};
}
通过跟进断点,我确保我正在发送一个有效的模型
我正在占用存储库模式,并且我的系统在我的 POST 操作中的以下行崩溃
await productoRepository.CreateAsync(producto);
我附上我的IProductoRepository.CS:
public interface IProductoRepository : IGenericRepository<Producto>
{
IQueryable GetAllWithCategories();
IQueryable GetAllWithUser();
IEnumerable<SelectListItem> GetComboProductos();
}
GenericRepository.CS:
public class GenericRepository<T> : IGenericRepository<T> where T : class, IEntity
{
private readonly DataContext context;
public GenericRepository(DataContext context)
{
this.context = context;
}
public async Task<T> CreateAsync(T entity)
{
await this.context.Set<T>().AddAsync(entity);
await SaveAllAsync();
return entity;
}
}
这是怎么回事?为什么我不能保存具有相应类别的产品?
我已经在我的 SQL 引擎中验证了我的各种密钥
我附上我的DataContext.CS作为附加信息:
public class DataContext : IdentityDbContext<User>
{
public DbSet<Producto> Productos { get; set; }
public DbSet<Category> Categories { get; set; }
#region Constructor
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
#endregion
//METODO QUE DESHABILITA EL BORRADO EN CASCADA
//Y ELIMINA LOS WARNING AL MIGRAR LA BASE DE DATOS
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//MANTISA DE 18 NUMEROS Y DOS DECIMALES
modelBuilder.Entity<Producto>().Property(p => p.Price).HasColumnType("decimal(18,2)");
//DESHABILITAR EL BORRADO EN CASCADA
var cascadeFKs = modelBuilder.Model
.GetEntityTypes()
.SelectMany(t => t.GetForeignKeys())
.Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);
foreach (var fk in cascadeFKs)
{
fk.DeleteBehavior = DeleteBehavior.Restrict;
}
base.OnModelCreating(modelBuilder);
}
}
}
我已尝试将以下 DataAnnotations 添加到我的相关课程中:
- [钥匙]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- [外键(“....”)]
还删除了数据库我又尝试了一切
我还验证了我的 SQL 的身份规范值
我知道这是一个已知的 ASP.NET Core 错误,但如何在 2.1 版中修复它?我是不是忘记了什么?对我有什么帮助吗?
解决方案
public class Category : IEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Nombre Categoría")]
[Required (ErrorMessage = "El campo categoría es obligatorio.")]
[MaxLength(30, ErrorMessage = "el campo {0} solo puede contener {1} caracteres de largo.")]
public string Name { get; set; }
public IList<Producto> Productos { get; set; }
}
public class Producto : IEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Nombre")]
[MaxLength(50, ErrorMessage = "El campo {0} ....")]
[Required]
public string Name { get; set; }
[Display(Name = "Descripción")]
[MaxLength(150, ErrorMessage = "El campo {0} solo puede contener {1}
caracteres de largo.")]
[Required]
public string Description { get; set; }
[Display(Name = "Precio")]
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Price { get; set; }
[Display(Name = "Imagen")]
public string ImageUrl { get; set; }
public User User { get; set; }
public int CategoryId { get; set; }
[ForeignKey(nameof(CategoryId))]
public Category Category { get; set; }
}
推荐阅读
- python - 如何在python中将kml文件解析为树结构?
- vba - 如何拆分包含“硬回报”的单元格
- c# - N-layered Web Api 使用 automapper 在控制器和服务层之间传递 DTO 错误
- android - 如何在 Ubuntu 和 Android 上使用英特尔 SGX 服务提供商证书?
- python - matlab 函数 strel("line") 到 python
- maven - Jenkins 无法识别 pom.xml 的文件路径
- guacamole - 鳄梨酱 - 服务器响应时间过长
- mysql - “在不存在的地方插入” - 在本地 (5.6.35) 上工作,但不在服务器 (5.7.22) 上工作 - 不显示错误
- ios - 带有整页单元格的 UICollectionView VS 带有子视图控制器的 UIScrollView
- php - 顶部有匹配项的订单标签