Vernon Maceda Vernon Maceda - 1 year ago 88
AngularJS Question

Redundancy in inserting random number in database - angularjs asp.net mvc

I got a

foreach loop
in my
angularjs controller


AccountController
angular.forEach($scope.accountList,function (account) {

AccountService.insertNewAccount(account).then(function (msg)
//some codes
});
});


In my AccountController.cs

int accountNo = GenerateRandomNo();
var chk = db.sp_check_account_number(accountNo).ToList(); //check if there's redudancy in generated AccountNumber in Account Table
var cnt = chk.Count;
if (cnt < 1)//If there is no redundancy
{
db.InsertNewAccount(name, accountNo);
}
else
{
//if there's redundancy generate another account number
while(cnt!=0)
{
accountNo = GenerateRandomNo();
chk = db.GetROPAAccount(accountNo).ToList();
cnt = chk.Count;
}
db.InsertNewAccount(name, accountNo);
}

db.SaveChanges();


My insert method in
AccountController.cs
functioning well but the problem is when it's done inserting the data came from
$scope.accountList
array, the inserted
AccountNumber
in the table record got many redundancy. I found out that my
foreach loop
inserted the data randomly and I don't know why. I also check my
sp_check_account_number
and it's working fine. Can someone help me with this? :(

Answer Source

You problem is with the GenerateRandomNo method. Currently you have this:

public int GenerateRandomNo()
{
    int min = 1000;
    int max = 9999;
    Random rdm = new Random();
    return rdm.Next(min, max);
}

There's your problem - Random rdm = new Random(); - if that's called in rapid succession you often get the same seed value so the values aren't random. Move this line out as a class-level variable and try again.

Do this:

private Random rdm = new Random();
public int GenerateRandomNo()
{
    int min = 1000;
    int max = 9999;
    return rdm.Next(min, max);
}

Also, as an extra thing, you're generating numbers from 1000 to 9998 when you use 1000 and 9999 as your input parameters. The second parameter is an exclusive maximum value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download