简体   繁体   English

SqlException:当 IDENTITY_INSERT 设置为 OFF ASP.NET Core 2.1 时,无法在表“类别”中插入标识列的显式值

[英]SqlException: Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF ASP.NET Core 2.1

When inserting a new product in my DB I am getting the following SQL error message:在我的数据库中插入新产品时,我收到以下 SQL 错误消息:

Form:形式:

创造

Error SQL:错误 SQL:

Sql

I have been looking for information about it and this is a SQL error that can be fixed from Entity Framework but I am not getting good results我一直在寻找有关它的信息,这是一个 SQL 错误,可以从实体框架中修复,但我没有得到好的结果

My models involved are the following...我所涉及的模型如下...

Producto.CS:产品.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; }
}

Category.CS:类别.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: IEntity.CS:

   public interface IEntity
   {
       int Id { get; set; }
            
   }

Attached my POST action of my product controller..附上我的产品 controller 的 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
            };
        }

By following up with a breakpoint I make sure that I am sending a valid model通过跟进断点,我确保我正在发送有效的 model

断点

I am occupying the repository pattern and my system crashes on the following line in my POST action我正在占用存储库模式,并且我的系统在我的 POST 操作中的以下行崩溃

 await productoRepository.CreateAsync(producto);

I attach my IProductoRepository.CS:我附上我的IProductoRepository.CS:

  public interface IProductoRepository :  IGenericRepository<Producto>
    {

        IQueryable GetAllWithCategories();

        IQueryable GetAllWithUser();

        IEnumerable<SelectListItem> GetComboProductos();

    }

GenericRepository.CS: 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;
        }
    }

What's going on?这是怎么回事? Why can't I save a product with its respective category?为什么我不能保存具有相应类别的产品?

I have verified my various keys in my SQL engine我已经在 SQL 引擎中验证了我的各种密钥

Sql

I am attaching my DataContext.CS as additional information:我附上我的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
                .G­etEntityTypes()
                .SelectMany(t => t.GetForeignKeys())
                .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Casca­de);

            foreach (var fk in cascadeFKs)
            {
                fk.DeleteBehavior = DeleteBehavior.Restr­ict;
            }

            base.OnModelCreating(modelBuilder);
        }
    }
    
        }

I have tried adding the following DataAnnotations to my classes in question:我已尝试将以下 DataAnnotations 添加到我的相关课程中:

  1. [Key] [钥匙]
  2. [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  3. [ForeignKey("....")] [外键(“....”)]

Also deleting the Database I have tried everything again还删除了数据库我又尝试了一切

I have also verified the Identity Specification value of my SQL我还验证了我的 SQL 的身份规范值

身份规范

I know this is a known ASP.NET Core bug, but how do I fix it in version 2.1?我知道这是一个已知的 ASP.NET 核心错误,但如何在 2.1 版中修复它? Am I forgetting something?我是不是忘记了什么? Any help for me?对我有什么帮助吗?

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; }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当IDENTITY_INSERT设置为OFF时,无法在TABLE中为Identity列插入显式值; .NET Core 2.1 - Cannot insert explicit value for identity column in TABLE when IDENTITY_INSERT is set to OFF; .NET Core 2.1 ASP.NET MVC 错误 SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“用户”中插入标识列的显式值 - ASP.NET MVC error SqlException: Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法为表 [表名] 中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'Ogretmenler' 中为标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Ogretmenler' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Recipe&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;AspNetUsers&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;&#39;中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table '' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“任务”中插入标识列的显式值 - SqlException: Cannot insert explicit value for identity column in table 'Tasks' when IDENTITY_INSERT is set to OFF ASP.net MVC 错误:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“公司”中插入标识列的显式值 - ASP.net MVC Error: Cannot insert explicit value for identity column in table 'Company' when IDENTITY_INSERT is set to OFF EF Core SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“MenuCategories”中插入标识列的显式值 - EF Core SqlException: Cannot insert explicit value for identity column in table 'MenuCategories' when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM