简体   繁体   English

实体框架C#-将数据从一个数据库移动到结构相似的另一个数据库

[英]Entity Framework C# - Moving data from one database to another with similar structure

I have two SQL Express databases, the first has alot of data in it, but we've build a new application that's going to run on a database that has similar table structures (added some columns, removed some, merged a few tables etc.). 我有两个SQL Express数据库,第一个数据库中有很多数据,但是我们已经建立了一个新的应用程序,该应用程序将在具有相似表结构的数据库上运行(添加了一些列,删除了一些,合并了一些表等)。 )。 The client is the same and they want to use the old data in the new application. 客户端是相同的,他们希望在新应用程序中使用旧数据。

So what I'm trying to do now is to move data (table by table) from the old DB, convert the entity (manually) from the old format to the new and then finally save that new entity in my new DB. 因此,我现在要做的是从旧数据库中移动数据(逐表),将实体(手动)从旧格式转换为新格式,然后最终将该新实体保存在我的新DB中。

I'm using Entity Framework and the server is ASP.NET Web Api. 我正在使用实体框架,服务器是ASP.NET Web Api。 I've created two seperate DbContext, one for the old DB and one for the new. 我创建了两个单独的DbContext,一个用于旧数据库,另一个用于新数据库。 I'm able to get my data from the old DB, transform it, but then I run into my issue, I need the Identity columns to stay the same, so that I can maintain the relationships that exists in the old DB, but when I try to save the entity, EF tells me that I can't insert value in the Identity Column when Identity_Insert is OFF. 我可以从旧数据库中获取数据,进行转换,但是随后遇到了问题,我需要Identity列保持不变,以便可以维护旧数据库中存在的关系,但是当我尝试保存实体,EF告诉我,当Identity_Insert为OFF时,我无法在“身份列”中插入值。

This is my actual Error message: 这是我的实际错误消息:

Cannot insert explicit value for identity column in table 'AccessoryProfiles' when IDENTITY_INSERT is set to OFF. 当IDENTITY_INSERT设置为OFF时,无法为表'AccessoryProfiles中的标识列插入显式值。

Here's my controller method that tries to migrate the data: 这是我的控制器方法,尝试迁移数据:

public IHttpActionResult Get()
        {
            try
            {
                var manager = new MigrationManager<AccessoryProfile>();

                var entities = manager.GetAll();


                foreach (var profile in entities)
                {
                    var newEntity = new Entities.Server.Accessories.AccessoryProfile
                    {
                        Id = profile.AccessoryProfileId,
                        Name = profile.Name,
                        CreatedDate = profile.CreatedDate,
                        LastModifiedDate = profile.LastModifiedDate,
                        DeletedDate = profile.DeletedDate
                    };

                    DataService.AccessoryProfile.Add(newEntity);
                }

                DataService.AccessoryProfile.Commit();

                return Ok();
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return null;
            }
        }

MigrationManager<T> handles the old DB while DataService handles the new one. MigrationManager<T>处理旧数据库,而DataService处理新数据库。 I've tried setting [DatabaseGenerated(DatabaseGeneratedOption.None)] on the Id, but no luck. 我试过在ID上设置[DatabaseGenerated(DatabaseGeneratedOption.None)],但是没有运气。 I've tried running this before my Commit(): 我试过在Commit()之前运行它:

DbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[AccessoryProfiles] ON");

...but I still can't insert a value in the Identity Column. ...但是我仍然无法在“身份列”中插入值。

How am I supposed to do this with Entity Framework? 我应该如何使用实体框架做到这一点? Or if you know of a better way than using EF, I'm all ears. 或者,如果您知道比使用EF更好的方法,那么我无所不能。 Thanks! 谢谢!

If you are inserting an entire table, I would recommend using EntityFramework.BulkInsert. 如果要插入整个表,则建议使用EntityFramework.BulkInsert。 For a lot of records, ".Add" or ".AddRange" extensions are pretty slow. 对于很多记录,“。Add”或“ .AddRange”扩展名非常慢。

Here is the description and speed advantages of bulkinsert: https://efbulkinsert.codeplex.com/ 这是bulkinsert的描述和速度优势: https ://efbulkinsert.codeplex.com/

在此处输入图片说明

You can also check out this thread for more info: Fastest Way of Inserting in Entity Framework 您还可以查看该线程以获取更多信息: 在Entity Framework中插入的最快方法

When setting up your SqlBulkCopy, it allows you to overload it with different SqlBulkCopyOptions. 设置SqlBulkCopy时,它允许您使用不同的SqlBulkCopyOptions重载它。 I believe one of them is "KeepIdentity" which allows you to keep the source identity. 我相信其中之一是“ KeepIdentity”,可让您保留源身份。 I think that might be what you're looking for. 我认为这可能是您要寻找的。

So when you set up your sqlbulkcopy object you might write something like this: 因此,当您设置sqlbulkcopy对象时,您可能会这样写:

SqlBulkCopy copy = new SqlBulkCopy(sqlConn, SqlBulkCopyOptions.KeepIdentity| SqlBulkCopyOptions.Default, null);

Also make sure you don't use the "CheckConstraints" option. 另外,请确保您不使用“ CheckConstraints”选项。

暂无
暂无

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

相关问题 更改数据库结构并在Entity Framework中移动数据 - Changing structure of database and moving data in Entity Framework 从sql服务器数据库迁移到不需要客户端安装服务器的数据库(C#Entity Framework) - Moving from a sql server database to one that doesn't require the client to install a server (C# Entity Framework) 实体框架将数据从一个数据库移动/归档到另一个数据库 - Entity framework move/archive data from one database to another c#在UWP中将数据从一个xaml移到另一个xaml - c# Moving data from one xaml to another xaml in UWP 在C#中使用实体框架在datagridview中显示数据库中的数据 - display data from database in datagridview with entity framework in c# 在C#中移动结构数据 - Moving structure data in C# 使用实体框架移动和比较来自不同数据库的数据 - Moving and comparing data from different database using entity framework 将datarow从一个表复制到另一个表中的另一个类似表c# - Copy datarow from one table to another similar table in different database c# .net / C#中有什么方法可以将表结构从一个数据库复制到另一个数据库? - Is there any way in .net/C# to copy a table structure from one database to another one? 如何在不将第一个实体插入Entity Framework C#中的数据库的情况下将实体ID分配给另一个实体? - How to assign entity Id to another entity without inserting first entity into database in Entity Framework, C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM