使用实体框架5将特定的ID插入到MySQL的自动递增字段中 [英] Insert a specific id into auto incremented field in MySQL with Entity Framework 5

查看:66
本文介绍了使用实体框架5将特定的ID插入到MySQL的自动递增字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的情况。

我有一个很旧的数据库,我的意思是大量的数据。不过,我最终创建了一个新的数据库结构,现在我想将数据从旧数据库移动到新数据库中。作为一个程序员,我不热衷于手动执行,这就是为什么我做了一个程序来做到这一点。

I have an old database with a lot, and I mean a LOT of data. However I've ended up creating a new database structure and now I want to move data from the old database into the new one. Being a programmer I'm not keen on doing it manually which is why I made a program to do just that.

现在这里是我的问题:添加一个新项目进入新的数据库,我无法设置它的id,这对于旧数据库中存在的不同链接引用和一般外键引用至关重要。

Now here is my problem: When adding a new item into the new database I'm unable to set it's id, which is crucial for the different link references and general foreign key references that exists in the old database.

我的问题因此:我可以通过实体在我的 MySQL 数据库中将指定的id 整数插入到具有 auto_increment 的字段中框架5 C#中首先使用数据库?

My question is therefore: How would I be able to insert an specified id integer into a field that has auto_increment in my MySQL database via Entity Framework 5 which uses database first in C#?


这是新数据库的MySQL脚本:

This is my MySQL script for the new database:

    CREATE TABLE Profile
    (
        _id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
        UNIQUE KEY(_id),
        etc etc
    )



我的插入代码:


My insert code:

    public Profile Add(Profile item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        db.Entry(item).State = EntityState.Added;
        db.SaveChanges();
        return item;
    }

在结尾的笔记中,我想知道这是不好的做法一般而言,数据库是空的,插入的id是从旧的数据库自动生成和唯一的,这将确保没有公开发生。

On an end note I whould like to inform that I know this is bad practise in general, but the database is empty and the id inserted are auto generated and unique from the old database which will ensure that no dublicates will occour

推荐答案

解决方案我在插入之前找到了更改表的位置。这基本上是其他人给出的解决方案,但是我需要转一圈。

The solution I found where to alter the table before inserting into it. It's basicly the solution other people gave, however I needed to make a few turns.

这就是我所做的:

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE Profile DROP PRIMARY KEY,
MODIFY _id INT PRIMARY KEY NOT NULL;

insert commmand here....

ALTER TABLE Profile DROP PRIMARY KEY,
MODIFY _id INT AUTO_INCREMENT PRIMARY KEY NOT NULL;

SET FOREIGN_KEY_CHECKS=1;

这篇关于使用实体框架5将特定的ID插入到MySQL的自动递增字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆