SQL Server Inserting data from one TSQL database table to another using C#

1mrurvl1  于 2023-05-05  发布在  C#
关注(0)|答案(2)|浏览(217)

We are working with the following class

internal class Person
{
        public int BusinessEntityID { get; set; }
        public string PersonType { get; set; }
        public bool NameStyle { get; set; }
        public string Title { get; set; }
        public  string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string Suffix { get; set; }
        public int EmailPromotion { get; set; }
        public string AdditionalContactInfo { get; set; }
        public Uri Demographics { get; set; }
        public string rowguid { get; set; }
        public DateTime ModifiedDate { get; set; }
}

The two databases are both active on localhost, suppose I also want to make it modular, is there any way that we can create the table inside Visual studio for the destination database so that no matter the entry it will always correspond to the end result?

This is my connection tab

internal class DestinationDatabase : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=localhost;Database=APIToDatabase;Trusted_Connection=True;TrustServerCertificate=True; MultipleActiveResultSets=true") ;

    }
    public DbSet<Person>? Person { get; set; }
}

internal class SourceDatabase : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=localhost;Database=AdventureWorks2019;Trusted_Connection=True;TrustServerCertificate=True; MultipleActiveResultSets=true");

    }
    public DbSet<Person>? Person { get; set; }
}

I attempted to create a reader that goes trough the entries one by one and inserts them into the destination, however I am not sure how to finalize it.

namespace DatabaseTransfer
{
    class Program
    {
        static void Main(string[] args)
        {
            var sourceDatabase = new SourceDatabase();
            var destinationDatabase = new DestinationDatabase();
            var constringsource = @"Server=localhost;Database=APIToDatabase;Trusted_Connection=True;TrustServerCertificate=True; MultipleActiveResultSets=true";
            var sourcecon = new Microsoft.Data.SqlClient.SqlConnection(constringsource);
            var constringdestination = @"Server=localhost;Database=AdventureWorks2019;Trusted_Connection=True;TrustServerCertificate=True; MultipleActiveResultSets=true";
            var destinationcon = new Microsoft.Data.SqlClient.SqlConnection(constringdestination);
            using (SqlCommand command = new SqlCommand("SELECT * FROM Person.Person", sourcecon))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            SqlCommand insert = new SqlCommand("INSERT INTO Person", destinationcon);
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
    }
}
9udxz4iz

9udxz4iz1#

Not quite got what you are trying to achieve and why are you mixing EF Core DbContext with ADO.NET's SQLConnection ,

but you could use your defined context to execute the SQL with EF CORE such way

using (var sourceContext = new SourceDatabase())
using (var destinationContext = new DestinationDatabase())
{
    var persons = sourceContext.Person.ToList();
    destinationContext.Person.AddRange(persons);
    destinationContext.SaveChanges();
}
vmjh9lq9

vmjh9lq92#

The ADO.net SqlBulkCopy class enables quick, mass upload of records into a table:

string csDestination = "put here the a connection string to the database";

using (SqlConnection connection = new SqlConnection(csDestination))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
    connection.Open()
    bulkCopy.DestinationTableName = "TUrls";
    bulkCopy.WriteToServer(dataTableOfUrls);
}

The EF BulkInsertAsync with EFCore.BulkExtensions. class enables quick, mass upload of records into a table:

var bulkConfig = new BulkConfig()
    {

        SetOutputIdentity = true,
                PreserveInsertOrder = true

    };
   

var ListPosts= schoolContext.Posts.ToList(); 
await schoolContext.BulkInsertAsync(ListPosts, bulkConfig);

相关问题