简体   繁体   中英

Merge data from two tables from different SQL Server database in C#

I have one central and two client database that have the same structure (identity id). The application allows users to merge data of selected tables from central db with one client db at a time.

For example:

[db_central].[table] :

+-------+-------+
| id    | name  |
+-------+-------+
| 1     | A     |
| 2     | B     |
| 3     | C     |
+---------------+

[db_client_1].[table] :

+-------+-------+
| id    | name  |
+-------+-------+
| 3     | D     |
+---------------+

[db_client_2].[table] :

+-------+-------+
| id    | name  |
+-------+-------+
| 3     | E     |
+---------------+

Expected result after merging (twice):

[db_central].[table] :

+-------+-------+
| id    | name  |
+-------+-------+
| 1     | A     |
| 2     | B     |
| 3     | C     |
| 4     | D     |
| 5     | E     |
+---------------+

Currently, I'm only able to load tables from database.

在此处输入图片说明

When user clicks "Manual Sync" button, the app will compare and merge data of selected tables from left to right database or vice versa.

If table doesn't exist, it will create the new one. If table does exist, it will compare and merge data but I don't know what is the best solution to accomplish this task.

Any suggestion would be appreciated.

Ideally you should have two columns at table in Central Database

  1. Primary key (with identity enabled)

  2. ChildKey (Primary Key of Child databases)

Primary key column in central database will take care of ordering, and chiild column will give you primary key in respective database

This seems like a simple sql query (if the databases are on the same server, or if you have a linked server between them) using except ...

insert into db_central       // Target table
select name from db_client_1 // Source table
except
select name from db_central  // Target table

If you have to do it in Linq, then it's very similar:

// Get the list of names to add
var newNames = dbContext.db_client_1.Select(e => e.name).Except(dbContext.db_central.Select(e => e.name));
// Convert the names to a list of entity objects and add them.
dbContext.db_central.Add(newNames.Select(e => new db_central { name = e.name });
dbContext.SaveChanges();

This is assuming you don't want duplicates in db_central

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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