gpt4 book ai didi

c# - MySqlException : Field 'id' doesn't have a default value - Entity Framework Core 2. 1

转载 作者:行者123 更新时间:2023-12-05 07:09:49 43 4
gpt4 key购买 nike

我是 ASP.NET Core MVC 的新手。我在使用 Entity Framework 核心向 MySQL 插入数据时遇到错误。调试时我得到了由上下文分配的 minus(-2147482645) 中的 id。为什么 id 是由 EF 分配的?如何解决这个错误? MySQL id 列中的表是 NOTNULL,PK 和 Auto Increment 设置为默认值。 enter image description here

这是我的 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 存在一些问题。从现在开始,我不会进行迁移,这会给我带来更多错误。

谢谢。

关于c# - MySqlException : Field 'id' doesn't have a default value - Entity Framework Core 2. 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61444923/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com