-1

In BooksList I have around 60k records and in Readers I have around 20 only.

Now, to populate the bridge table (many-to-many) I have to assign each BookList record at least 2 Readers.

It's done but on the loading of app for the first time, it takes around ~30 seconds.

Is it normal?

Is there any way to speed it up?

Note: this is the requirement and I have to do it this way means I have to seed the data on the first load but my concern is performance.

foreach (var n in BooksList)   //60k records
{
    int innerLoopCounter = 0;

    foreach (var t in ReadersList)  //only 20 registered readers
    {
        BooksReadersList.Add(new BooksReaders() { BooksID = n.BooksID, ReaderID = t.ReaderID });

        innerLoopCounter++;

        if (innerLoopCounter > 2)   //should not be more than 2.
            break;
        
    }
}


BooksDbContext.BooksReaders.AddRange(BooksReadersList);

BooksDbContext.ChangeTracker.DetectChanges();

base.Seed(BooksDbContext);

The BooksReadersList is a list of type BookReaders which has 3 columns (ID, Book_ID, Reader_ID).

The BooksList is a list of type Books which as 2 columns (ID, BookTitle) and ReaderList is a list of type Readers which as 2 columns (ID, ReaderName).

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Lucifer
  • 3
  • 4

1 Answers1

0

I'm guessing here based on the code shown in the question. I created a LINQ-style Cartesian product of BooksList and the first two readers from ReadersList, based on this answer by McKay to Is there a good LINQ way to do a cartesian product?. I don't know if this will be faster, but it moves the looping out of user code. Hopefully, EF will translate that into some efficient SQL. Not as efficient as SqlBulkCopy or plain old SQL statements written out, but given the constraints...

var BooksReadersList = BooksList.SelectMany((b) => ReadersList.Take(2), 
    (book, readers) => readers.Select(reader => new BooksReader 
        { book.BooksID, reader.ReaderID }));

BooksDbContext.BooksReaders.AddRange(BooksReadersList);

BooksDbContext.ChangeTracker.DetectChanges();

base.Seed(BooksDbContext);
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122