More efficent and quickier way to generate numbers and insert into db
Hi all i have the following bit of code, which is used to generate telephone numbers and insert these into a table in a database. To generate the codes it looks in a table in the database to see which "F" digit numbers need generating for a range. So for example the Leeds range of "01132 21", needs numbers generating for 1,3,4 and 6. So the numbers generated would be like 01132211000-01132211999, 01132213000-01132213999, etc.
This is working as i wanted and as expected. However it is taking quite a long time (taken 12 hours to generate 120,000 records and i estimate we could have roughly a one million records generated. Just wondering if there is a quicker way to do what i want. I'm still a very "green" developer, so dont really know the best way to do things quite yet!
private TelephoneNumberManagementEntities context = new TelephoneNumberManagementEntities();
public ActionResult Index()
{
var list = context.TempNumberImports.ToList();
foreach (var item in list)
{
string range = item.Range.ToString().Trim().Replace(" ","");
if (item.C0 == "Y")
{
GenerateNumbers(range, 0开发者_开发问答, 999, item.ID);
}
if (item.C1 == "Y")
{
GenerateNumbers(range, 1000, 1999, item.ID);
}
if (item.C2 == "Y")
{
GenerateNumbers(range, 2000, 2999, item.ID);
}
if (item.C3 == "Y")
{
GenerateNumbers(range, 3000, 3999, item.ID);
}
if (item.C4 == "Y")
{
GenerateNumbers(range, 4000, 4999, item.ID);
}
if (item.C5 == "Y")
{
GenerateNumbers(range, 5000, 5999, item.ID);
}
if (item.C6 == "Y")
{
GenerateNumbers(range, 6000, 6999, item.ID);
}
if (item.C7 == "Y")
{
GenerateNumbers(range, 7000, 7999, item.ID);
}
if (item.C8 == "Y")
{
GenerateNumbers(range, 8000, 8999, item.ID);
}
if (item.C9 == "Y")
{
GenerateNumbers(range, 9000, 9999, item.ID);
}
}
return View();
}
public void GenerateNumbers(string range, int startNo, int endNo, int rangeID)
{
Number num = new Number();
for (int i = startNo; i <= endNo; i++)
{
if (startNo == 0)
{
string tempNum = range + i.ToString("D4");
var record = context.Numbers.FirstOrDefault(m => m.Number1 == tempNum);
if (record == null)
{
num.Number1 = tempNum;
num.RangeID = rangeID;
num.StatusID = 1;
num.ImportDate = DateTime.Now;
num.ImportSource = "Number Ranges 250811.xlsx";
context.Numbers.Add(num);
context.SaveChanges();
}
}
else
{
string tempNum = range + i;
var record = context.Numbers.FirstOrDefault(m => m.Number1 == tempNum);
if (record == null)
{
num.Number1 = tempNum;
num.RangeID = rangeID;
num.StatusID = 1;
num.ImportDate = DateTime.Now;
num.ImportSource = "Number Ranges 250811.xlsx";
context.Numbers.Add(num);
context.SaveChanges();
}
}
}
}
Simple answer: USE STORED PROCEDURE
Your current solution will produce thousands of database roundtrips because every single number will be inserted in separate database call.
You can also consider preparing data as batch and use SqlBulkCopy
.
精彩评论