Reputation: 25308
I have this sample code (.NET Core 2.2):
private void IterateSave(List<TokenMaster> items, int min, int max)
{
int skip = min;
int take = max / 5;
while (skip <= max)
{
try
{
var subItems = items.Skip(skip).Take(take).ToList();
_db.TokenMasters.AddRange(subItems); // <---
_db.SaveChanges();
skip += take;
}
catch (Exception ex)
{
Log.Error(ex, "Error saving this data batch! {RecordCount}", take);
IterateSave(items, skip, take);
}
}
}
private void IterateSave(List<Attributes> items, int min, int max)
{
int skip = min;
int take = max / 5;
while (skip <= max)
{
try
{
var subItems = items.Skip(skip).Take(take).ToList();
_db.Attributes.AddRange(subItems); // <---
_db.SaveChanges();
skip += take;
}
catch (Exception ex)
{
Log.Error(ex, "Error saving this data batch! {RecordCount}", take);
IterateSave(items, skip, take);
}
}
}
How would you turn this into a single generic call? I am struggling with the DbSet
and Model
being required.
Upvotes: 0
Views: 54
Reputation: 14578
Is it not as simple as:
private void IterateSave<T>(List<T> items, int min, int max) where T : class
{
int skip = min;
int take = max / 5;
while (skip <= max)
{
try
{
var subItems = items.Skip(skip).Take(take).ToList();
_db.Set<T>().AddRange(subItems);
_db.SaveChanges();
skip += take;
}
catch (Exception ex)
{
Log.Error(ex, "Error saving this data batch! {RecordCount}", take);
IterateSave(items, skip, take);
}
}
}
Upvotes: 2