I have a database which contains 2 tables:
Apartment: ID, Name, Address
Tenant: ID, Name, Phone, ApartmentID
Each apartment can have more than one tenant, but each tenant can be in only one apartment.
There is also an API that returns the current list of apartments, and a list of tenants that are in that apartment as a JSON list:
Apartments : [
{
Name: 'Sherwood',
Address: '21 Woody Lane' ,
Tenants : [
{ Name: 'Robin', Phone: '111-1111' },
{ Name: 'Hood', Phone: '222-2222' }
]
},
...
]
I need to parse the API result into 2 related objects, apartment and tenant, and insert them into the database. There are a lot of entries returned from the API, about 500,000. In order to quicken things up, I have taken ideas from: Fastest Way of Inserting in Entity Framework
However, there is one concept from that post that I am unable to implement in my solution, i.e. deferring SaveChanges(). This is how I have the code (conceptual) currently:
Foreach apartment
Insert apartment into DB
SaveChanges()
Get ID of inserted apartment
Foreach tenant in apartment
Insert tenant into DB, into apartment ID
The reason for the above structure is, when inserting a tenant row, I need the apartment ID that that tenant is living in, and therefore I need to have inserted (and saved changes to get the ID of) the apartment prior to inserting the tenant.
This is leading to SaveChanges() being called many times and hurting performance. How can the above solution be optimized?