我需要使用Entity Framework将数据从数据库中的旧表复制到新表中(我在SQL中无法做到),但这非常慢。 如何加快速度?
我检查方法SaveChanges()
消耗了30%的CPU-很奇怪。也许不要将相关实体另存为:X.File = userFile
-我应该写:X.FileId = userFile.Id
?
private void CopyFile(FileFromForm oldFileFromForm)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
var userSheetsRelatedWithForm = _dbContext.UserRelatedwithForm.AsNoTracking()
.Include(x => x.Sheet)
.Where(x => x.FormId == oldFileFromForm.FormId)
.ToList();
UserFiles userFile = new UserFiles();
newCandidateFile.CandidateId = userSheetsRelatedWithForm.First().UserId;
newCandidateFile.FileFormatId = 1;
newCandidateFile.FileTypeId = 2;
newCandidateFile.CompanyId = oldFileFromForm.CompanyId;
newCandidateFile.FileName = oldFileFromForm.FileName;
_dbContext.UserFiles.Add(userFile);
FormFiles formFile = new FormFiles();
formFile.FormId = oldFileFromForm.FormId;
formFile.File = userFile; // Can it be: formFile.FileId = userFile.Id ?
_dbContext.FormFiles.Add(formFile);
foreach (var sheetId in userSheetsRelatedWithForm.Select(x => x.SheetId).Distinct())
{
UserFilesWithSheets userFilesWithSheet = new UserFilesWithSheets();
userFilesWithSheet.SheetId = sheetId;
userFilesWithSheet.File = userFile; // Can it be: userFilesWithSheet.FileId = userFile.Id ?
_dbContext.UserFilesWithSheets.Add(userFilesWithSheet);
}
_dbContext.SaveChanges(); // It consumes 30% CPU !!!
transaction.Commit();
}
}