简体   繁体   English

通过实体框架将具有指定主键的记录插入MySQL

[英]Inserting a record with specified primary key into MySQL via Entity Framework

We began using Entity Framework with MySQL in our project recently. 我们最近开始在我们的项目中将Entity Framework与MySQL结合使用。 Now I am writing unit tests for the data access level; 现在,我正在为数据访问级别编写单元测试; for that purpose I have created a database with some test data. 为此,我创建了一个包含一些测试数据的数据库。

In the test-method for the Delete method I want to first delete a specified record and then insert it again with all the fields holding exactly the same values, including the Id column which is set as the primary key. 在Delete方法的测试方法中,我想首先删除指定的记录,然后再次插入所有具有完全相同值的字段,包括设置为主键的Id列。 The purpose is to keep the test data in the DB. 目的是将测试数据保留在数据库中。

But when I insert previously deleted record, Entity Framework just ignores the Id value of the entity and thus a new Id is generated using AUTO_INCREMENT. 但是,当我插入以前删除的记录时,实体框架只是忽略了实体的ID值,因此使用AUTO_INCREMENT生成了一个新的ID。

Thanks in advance. 提前致谢。

Have you used the insert ignore statement? 您是否使用了插入忽略语句?

It helps you forcefully insert pks with specified value. 它可以帮助您强行插入具有指定值的pk。

AUTO_INCREMENT means that you do not get to set the Id value, period. AUTO_INCREMENT意味着您无法设置Id值,即周期。 You just can't do this. 你就是做不到。

What you should do instead is: 相反,您应该做的是:

  1. Insert a new row. 插入新行。
  2. SaveChanges()
  3. Now read the Id value on the object, which will have been updated from the database. 现在读取对象的Id值,该值将从数据库中更新。
  4. Go ahead and delete the row, using this Id value. 继续并使用此ID值删除该行。

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

相关问题 使用实体框架插入实体后主键保持为空 - Primary key stays null after inserting Entity with Entity Framework 在使用实体框架插入时,为什么MySQL在唯一索引约束中不包括主键? - Why does MySQL not include the primary key in a unique index constraint when inserting with the Entity Framework? 插入新记录时,mysql实体框架6“字段为必填”错误 - mysql entity framework 6 “field is required” error while inserting new record MySql实体框架数据库优先-主键=长? - MySql Entity Framework Database First - Primary Key = Long? 实体框架中的主键未增加 - Primary Key not incrementing in Entity Framework 没有主键的mysql上的弱实体 - Weak entity on mysql with no primary key MySQL 在主键中插入值为 0 的行 - MySQL inserting rows with 0 value in primary key 使用实体框架的主键(数据库优先) - Primary Key (Database First) using entity framework Mysql Entity Framework 问题 - 指定的键太长; 最大密钥长度为 3072 字节 - Mysql Entity Framework issue - Specified key was too long; max key length is 3072 bytes 指定密钥太长; 最大密钥长度为767字节实体框架6中的Mysql错误 - Specified key was too long; max key length is 767 bytes Mysql error in Entity Framework 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM