[英]Redundancy in inserting random number in database - angularjs asp.net mvc
我的angularjs controller
有一個foreach loop
AccountController
angular.forEach($scope.accountList,function (account) {
AccountService.insertNewAccount(account).then(function (msg)
//some codes
});
});
在我的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();
我在AccountController.cs
插入方法運行良好,但問題是當完成數據插入時,該數據來自$scope.accountList
數組,因此在表記錄中插入的AccountNumber
有很多冗余。 我發現我的foreach loop
隨機插入了數據,我不知道為什么。 我還檢查了我的sp_check_account_number
,它工作正常。 有人可以幫我弄這個嗎? :(
您的問題是GenerateRandomNo
方法。 目前您有:
public int GenerateRandomNo()
{
int min = 1000;
int max = 9999;
Random rdm = new Random();
return rdm.Next(min, max);
}
有您的問題Random rdm = new Random();
-如果快速連續調用,則通常會獲得相同的種子值,因此這些值不是隨機的。 將此行作為類級變量移出,然后重試。
做這個:
private Random rdm = new Random();
public int GenerateRandomNo()
{
int min = 1000;
int max = 9999;
return rdm.Next(min, max);
}
另外,另外,當您使用1000
和9999
作為輸入參數時,會生成從1000
到9998
數字。 第二個參數是互斥最大值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.