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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Amit MohantyPosted Jun 9, 2023, 12:14 PM
You can call that class like:
Tuhin PaulPosted Jun 10, 2023, 12:16 PM
1. Set up your DbContext:
2. Create a method in your console application to perform the record copy:
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.
Mic GotPosted Jun 9, 2023, 4:14 PM
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!
Mic GotPosted Jun 9, 2023, 11:49 AM
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();
}
}
Vishal JoshiPosted Jun 9, 2023, 8:40 AM
Hello Mic
You can try the below code with your table and column name.
Thanks