I am writing an importer service. I have different sources and at the end I would like to push them into database tables.
For different db tables, I am using different dbset in the context. I also am aware for each db what is the primary key (it could be different, because other naming conversation).
I would like to resolve the issue, and refactor this code into 1 common, where I just have to name the Entity DbSet, and give the primary key, and everything is just working smooth with the given configuration:
var fmResultIds = fmResultset.Resultset.Records.Select(r => r.Fields.First(f => f.Name == primaryKeyName).Value).ToArray(); switch (config.Value.GetTableName()) { case "FmCompanyIntegration1": // The FMCompanyIntegration1 should be a parameter var allsql1 = context.Set<FmCompanyIntegration1>() .Where(t => true) //The issue here, the primary key should be a parameter .Where(t => fmResultIds.Contains(t.CoId)) .Take(100000) .ToDictionary(kvp => kvp.CoId, kvp => kvp); //this is taking care to update/insert the record. We do not have to delete anything foreach (var record in fmResultset.Resultset.Records) { var entity = allsql1.FirstOrDefault(r => r.Key == record.Fields.First(f => f.Name == primaryKeyName).Value).Value; if (entity != null) { // LoadRecord is not a problem, because all entity is coming from the same base class, which has this function defined entity.LoadRecord(record); context.Entry(entity).State = EntityState.Modified; updated++; } else { // here I also have to dynamically create the class... entity = new FmCompanyIntegration1(); entity.LoadRecord(record); context.Entry(entity).State = EntityState.Added; inserted++; } } break; // full copypaste from above. I would like to get rid of this obviously case "FmBookBackyard1": default: var allsql2 = context.Set<FmBookBackyard1>() .Where(t => true) // Again I know what is the primary key field name... Or I am ready to extend any reasonable class to give it back .Where(t => fmResultIds.Contains(t.BkRecordId)) .Take(100000) .ToDictionary(kvp => kvp.BkRecordId, kvp => kvp); //this is taking care to update/insert the record. We do not have to delete anything foreach (var record in fmResultset.Resultset.Records) { var entity = allsql2.FirstOrDefault(r => r.Key == record.Fields.First(f => f.Name == primaryKeyName).Value).Value; if (entity != null) { entity.LoadRecord(record); context.Entry(entity).State = EntityState.Modified; updated++; } else { entity = new FmBookBackyard1(); entity.LoadRecord(record); context.Entry(entity).State = EntityState.Added; inserted++; } } break; } context.SaveChanges();