原因:
數據庫中的兩個表是主從表關系,但是沒有建外鍵,而表的id用的是數據庫的自增整數,導致在使用EF導入主從表數據時,需要先保存主表數據,取到
主表的自增id后才能插入從表數據,這樣循環之下,數據插入速度非常慢。
經過查詢得知:
即使在數據庫中沒有建立外鍵關系,也可以在EF中通過關系建議主從表關系,從而達到批量導入主從表數據的目的。
具體實現:
首先model中需要添加主從表的關系屬性
主表
[Table("DataHubEmployee")] public partial class DataHubEmployee : SecuredEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int pkDataHubEmployee { get; set; } public int fkDataHubBatch { get; set; } public int? OriginalBatchId { get; set; } public int EmployeeId { get; set; } public string ClientCode { get; set; } public virtual ICollection<DataHubDependant> DataHubDependants { get; set; } }
從表
[Table("DataHubDependant")] public partial class DataHubDependant : SecuredEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int pkDataHubDependant { get; set; } public int? OriginalBatchId { get; set; } public string ClientCode { get; set; } public int fkDataHubEmployee { get; set; } public string EmployeeId { get; set; } public string FullName { get; set; } public virtual DataHubEmployee DataHubEmployee { get; set; } }
然后EF的DbContext中的OnModelCreating對實體的外鍵關聯進行注冊
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Properties<decimal>().Configure(c => c.HasPrecision(18, 6)); //add model mapping for auto process modelBuilder.Entity<DataHubDependant>() .HasRequired(d => d.DataHubEmployee) .WithMany(e => e.DataHubDependants) .HasForeignKey(d => d.fkDataHubEmployee); modelBuilder.Entity<DependantChangeLog>() .HasRequired(d => d.EmployeeChangeLog) .WithMany(e => e.DependantChangeLogs) .HasForeignKey(d => d.fkEmployeeChangeLog); //close auto migration Database.SetInitializer<ClientDbContext>(null); base.OnModelCreating(modelBuilder); }
說明:這里可以通過.HasForeignKey(d => d.fkDataHubEmployee);來指定從表中的哪個字段是外鍵。如果不指定,EF會自動生產一個包含外鍵的新列。
批量插入數據
foreach (var dataHubEmployeeDTO in dataHubEmployeeDtoList) { if (batchType == "MonthlyData" && dataHubEmployeeDTO.Status.ToUpper() == "Terminated".ToUpper()) { continue; } DataHubEmployee dataHubEmployee = new DataHubEmployee { EmployeeId = dataHubEmployeeDTO.EmployeeId, fkDataHubBatch = dataHubBatch.pkDataHubBatch, OriginalBatchId = batchId, ClientCode = dataHubEmployeeDTO.ClientCode, DataHubDependants = new List<DataHubDependant>() }; //插入重表數據 //獲取當前批員工列表 foreach (var dependant in dataHubEmployeeDTO.DependantList) { var dataHubDependant = new DataHubDependant { OriginalBatchId = batchId, ClientCode = dataHubEmployeeDTO.ClientCode, fkDataHubEmployee = dataHubEmployee.pkDataHubEmployee, EmployeeId = dataHubEmployeeDTO.ID, FullName = dependant.FullName, Identification = dependant.Identification, BirthDate = dependant.BirthDate, Gender = dependant.Gender, Nationality = dependant.Nationality, }; dataHubEmployee.DataHubDependants.Add(dataHubDependant); } clientDbContext.DataHubEmployee.Add(dataHubEmployee); } clientDbContext.SaveChanges();
這樣就可以在批量插入數據的時候,自動填充主表的自增ID到從表。
