Hi,
How to copy record between tables with entity framework core in a console application
using dbcontext?
thks
Hi,
How to copy record between tables with entity framework core in a console application
using dbcontext?
thks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Jun 9, 2023, 8:14 AM EDT
You can call that class like:
static void Main(string[] args) { using (var dbContext = new DataContext()) { var recordCopyService = new RecordCopyService(dbContext); recordCopyService.CopyRecords(); } }Vishal JoshiRank #377 · 6.7K reputationPosted Jun 9, 2023, 4:40 AM EDT
Hello Mic
You can try the below code with your table and column name.
dbContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "INSERT INTO T2 (col1, col2, ...) SELECT col1,col2, ... FROM T1");Thanks
Mic Got91 reputationPosted Jun 9, 2023, 7:49 AM EDT
hi,
I have used the first reply code (see below) , now i would like to call this class from my program.cs.
How can i do it?
Thks again
public RecordCopyService(DataContext dbContext)
{
_dbContext = dbContext;
}
public void CopyRecords()
{
var sourceRecords = _dbContext.Departments.ToList();
foreach (var sourceRecord in sourceRecords)
{
var destinationRecord = new DepartmentCopy
{
DepartmentCopyId = sourceRecord.DepartmentId,
Name = sourceRecord.Name,
GroupName = sourceRecord.GroupName,
ModifiedDate = sourceRecord.ModifiedDate,
};
_dbContext.DepartmentCopies.Add(destinationRecord);
}
_dbContext.SaveChanges();
}
}
Mic Got91 reputationPosted Jun 9, 2023, 12:14 PM EDT
the application now copy the record without a check if exist or not on the destination table
so i have modified the code as follow:
****
public void CopyRecords()
{
var sourceRecords = _dbContext.Departments.ToList();
foreach (var sourceRecord in sourceRecords)
{
var dbValue = _dbContext.GetDepartmentCopyById(sourceRecord.DepartmentId);
var destinationRecord = new DepartmentCopy
{
DepartmentCopyId = sourceRecord.DepartmentId,
Name = sourceRecord.Name,
GroupName = sourceRecord.GroupName,
ModifiedDate = sourceRecord.ModifiedDate
};
if (dbValue == null)
{
_dbContext.DepartmentCopies.Add(destinationRecord);
}
else
{
_dbContext.DepartmentCopies.Update(destinationRecord);
}
_dbContext.SaveChanges();
}
}
}
but i got this error when i try to update ...
System.InvalidOperationException: 'The instance of entity type 'DepartmentCopy' cannot be tracked because another instance with the same key value for {'DepartmentCopyId'} is already being tracked.
thks a lot for any ideas!
Tuhin PaulRank #7 · 71.9K reputationPosted Jun 10, 2023, 8:16 AM EDT
1. Set up your DbContext:
public class YourDbContext : DbContext { public DbSet SourceEntities { get; set; } public DbSet DestinationEntities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // Configure your database connection optionsBuilder.UseSqlServer("YourConnectionString"); } }2. Create a method in your console application to perform the record copy:
public static void CopyRecords() { using (var dbContext = new YourDbContext()) { // Retrieve records from the source table var sourceRecords = dbContext.SourceEntities.ToList(); foreach (var sourceRecord in sourceRecords) { // Create a new record in the destination table var destinationRecord = new DestinationEntity { // Set the properties of the destination record based on the source record Property1 = sourceRecord.Property1, Property2 = sourceRecord.Property2, // Set other properties as needed }; // Add the new record to the destination table dbContext.DestinationEntities.Add(destinationRecord); } // Save changes to persist the new records dbContext.SaveChanges(); } }Replace YourDbContext, SourceEntity, DestinationEntity, and the connection string (YourConnectionString) with your actual DbContext class and entity names, as well as your specific database connection details. By calling the CopyRecords method, you can copy records from the source table (SourceEntities) to the destination table (DestinationEntities) using Entity Framework Core in your console application.