简体   繁体   English

在数据库中插入随机数的冗余-angularjs asp.net mvc

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

I got a foreach loop in my angularjs controller 我的angularjs controller有一个foreach loop

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

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

In my AccountController.cs 在我的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. 我在AccountController.cs插入方法运行良好,但问题是当完成数据插入时,该数据来自$scope.accountList数组,因此在表记录中插入的AccountNumber有很多冗余。 I found out that my foreach loop inserted the data randomly and I don't know why. 我发现我的foreach loop随机插入了数据,我不知道为什么。 I also check my sp_check_account_number and it's working fine. 我还检查了我的sp_check_account_number ,它工作正常。 Can someone help me with this? 有人可以帮我弄这个吗? :( :(

You problem is with the GenerateRandomNo method. 您的问题是GenerateRandomNo方法。 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(); 有您的问题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. 另外,另外,当您使用10009999作为输入参数时,会生成从10009998数字。 The second parameter is an exclusive maximum value. 第二个参数是互斥最大值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM