Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Nathaniel 5 posts 85 karma points
    Aug 10, 2021 @ 11:53
    Nathaniel
    0

    Best Practice for importing data into custom database table when looping

    Hello everyone, hope you'll are having a fine morning/evening.

    I was able to import a list of Students along with their Subject in bulk. I am able to do so with the follow approach. The list mostly is in thousands.

     using(var scope = _scopeProvider.CreateScope()) {
       var db = scope.Database;
    
       for (var i = 0; i < items.Count; i++) {
    
         //insert student record
         var student = items[i].Student;
         db.Insert(student);
    
         //insert subject record
         var subject = items[i].Subject;
         db.Insert(subject):
       }
       scope.Complete();
     }
    

    Is this approach correct where I am looping through all the items and then calling Scope.Complete() or should I call Scope.Complete on each iteration.

  • Huw Reddick 1932 posts 6722 karma points MVP 3x c-trib
    Aug 10, 2021 @ 12:15
    Huw Reddick
    0

    I would create all the objects and do a batch insert.

    so define a list of students and add them in your loop and then do a batch insert

            List<Student> students = new List<Student>();
            Loop to add students to list ...
    
            using (var transaction = scope.Database.GetTransaction())
            {
                var database = scope.Database; 
                database.InsertBatch<Student>(students);
                transaction.Complete();
            }
    
  • Nathaniel 5 posts 85 karma points
    Aug 10, 2021 @ 14:19
    Nathaniel
    0

    I like this approach, but say if I want tocheck if the record exists or not and only then insert or update. Can you please advise on what should be the way to go for this scenario?

  • Brendan Rice 538 posts 1102 karma points
    Aug 10, 2021 @ 14:33
    Brendan Rice
    0

    A batch approach wouldn't work if you need to perform checks.

    An alternative would be to have a secondary table (same schema as students, it could be a temp table). Batch import into it, then at the end of the batch INSERT INTO the main student table where the students didn't already exist.

  • Huw Reddick 1932 posts 6722 karma points MVP 3x c-trib
    Aug 10, 2021 @ 16:08
    Huw Reddick
    1

    I would agree with Brendan if you need to check for existence.

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies