繁体   English   中英

MySqlException:字段 'id' 没有默认值 - Entity Framework Core 2.1

[英]MySqlException: Field 'id' doesn't have a default value - Entity Framework Core 2.1

我是 ASP.NET 核心 MVC 的新手。 我在使用实体框架核心向 MySQL 插入数据时出错。 在调试时,我得到了上下文分配的减号(-2147482645)中的 id。为什么 id 是由 EF 分配的? 如何解决此错误? MySQL id 列中的表为 NOTNULL,PK 和 Auto Increment 设置为默认值。 在此处输入图像描述

这是我的 DBContextFile

    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        { }

        public DbSet<PCBDesign> pCBDesigns { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

这是我的 Class

    {

        [Key]
        public int id { get; set; }
        public string userId { get; set; }
        public string desginNo { get; set; }
        public DateTime Crdate { get; set; }
        public string name { get; set; }
        public string contact { get; set; }
        public string notes { get; set; }
    }

调用后context.SaveChanges(); 得到错误:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Field 'id' doesn't have a default value ---> MySql.Data.MySqlClient.MySqlException: Field 'id' doesn't have a default value

建表查询:

DROP TABLE IF EXISTS `pcbdesigns`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `pcbdesigns` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  `desginNo` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  `Crdate` datetime NOT NULL,
  `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  `contact` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  `notes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `pcbdesigns`
--

LOCK TABLES `pcbdesigns` WRITE;
/*!40000 ALTER TABLE `pcbdesigns` DISABLE KEYS */;
INSERT INTO `pcbdesigns` VALUES ();
/*!40000 ALTER TABLE `pcbdesigns` ENABLE KEYS */;
UNLOCK TABLES;`

问题已解决: 第 1 步:为每个表复制表创建脚本第 2 步:从同一脚本创建的已删除表。 第 3 步:在表格中添加一个虚拟行。

附加信息:我从代码优先方法进行了迁移,我认为迁移时 Entity Framework Core 存在一些问题。 从现在开始,我不会进行迁移,这会给我带来更多错误。

谢谢。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM