question

SantoshUmarani-1390 avatar image
0 Votes"
SantoshUmarani-1390 asked JackJJun-MSFT answered

SqlBulkCopy of EntiryFramework table

Hi,

I have a LogHistory table which is available in Entity framework. I have set of values to be set in this table. If I set like below for individual values, I am able to set the values in LogHistory table.

using (var context = new AutomationEntities())
{
var log = new LogHistory
{
UserName = GetUserName(),
UserId = GetUserId(),
ActionPerformed = "EditTestCase"
}
context.LogHistories.Add(log);
context.SaveChanges();
}

However, I wanted to set these values using bulkcopy. I have all the data in "dataTable". The updated values are being set in LogHistory table. I guess I am setting DestinationTableName wrongly.

using (var context = new AutomationEntities())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = "dbo.LogHistory";
bulkCopy.WriteToServer(dataTable);
}
}

Can you please suggest how should I set DestinationTableName in this case ? Kindly waiting for your response.

Thanks,
Santosh

sql-server-generaldotnet-csharpdotnet-entity-framework
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JackJJun-MSFT avatar image
0 Votes"
JackJJun-MSFT answered

@SantoshUmarani-1390, Welcome to Microsoft Q&A, based on my test, there is no error for me if you want to copy data from datatable to database.

I make a code example and you could refer to it.

  static void Main(string[] args)
         {
            TestEntities1 test=new TestEntities1();
    
             DataTable table = GetDataTable();
             SqlConnection connection = new SqlConnection(test.Database.Connection.ConnectionString);
             connection.Open();
             using (SqlBulkCopy s = new SqlBulkCopy(connection))
             {
                 //set the table name
                 s.DestinationTableName = "dbo.LogHistory";
    
                 foreach (var column in table.Columns)
    
                     s.ColumnMappings.Add(column.ToString(), column.ToString());
    
                 s.WriteToServer(table);
             }
             connection.Close();
         }

Result in Database:

195543-image.png



Hope this could help you.

Best Regards,
Jack


If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


image.png (4.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.