微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试创建唯一的随机数如果数据库中存在数字,则再次生成并为数据库添加值

如何解决尝试创建唯一的随机数如果数据库中存在数字,则再次生成并为数据库添加值

我正在尝试创建一个唯一的随机数。如果数据库中存在随机数,请再次遍历代码块,直到找到不存在的数字。将价值保存到数据库。任何帮助都会很棒。谢谢。

public IHttpActionResult BookMatch(int id)
{
    Guid guid = Guid.NewGuid();

    var user = User.Identity.GetUserId();
    var getuser = db.AspNetUsers.Find(user);
    var match = db.Matches.Find(id);

    Random rnd = new Random();
    var peg = rnd.Next(match.PegRangeMin,match.PegRangeMax);

    var alreadyExists = db.Pegs.Any(x => x.MatchId == match.Id && x.PegNo == peg);

    if (alreadyExists == true)
    {
        //do something
    }

    var result = new Booked()
    {

        MatchId = id,BookerId = user,TicketNo = guid.ToString(),//pegNo = randompeg
    };

    db.Bookeds.Add(result);
    db.SaveChanges();

    if (result == null)
    {
        throw new Exception();
    }

    var getmatch = db.Matches.Find(id);

        var body = "<p>Email From: {0} ({1}) </p>" +
                   "<h3>Match Booking Confirmation:</h3>" +
                   "<b>Ticket Number:</b><p> {2} </p>" +
                   "<b>Venue:</b><p> {3} </p>" +
                   "<b>date and time:</b><p>{4}</p>";

        var message = new MailMessage();
        message.To.Add(new MailAddress(getuser.Email));
        message.From = new MailAddress("nicholas.mciver@Activeplan.co.uk");
        message.Subject = "Matchbooker Confirmation Email";
        message.Body = string.Format(body,getuser.GetFullName(),getuser.Email,result.TicketNo,getmatch.Fishery.Name,getmatch.DateTime);
        message.IsBodyHtml = true;

        using (var smtp = new SmtpClient())
        {
            smtp.Send(message);
        }

    return Ok();
}

解决方法

最简单的方法是在int peg; while (true) { peg = rnd.Next(match.PegRangeMin,match.PegRangeMax); var alreadyExists = db.Pegs.Any(x => x.MatchId == match.Id && x.PegNo == peg); if (!alreadyExists) break; } 循环中进行数字生成和检查:

# start Excel
$excel = New-Object -comobject Excel.Application

#open file
$FilePath = 'FilePath'
$workbook = $excel.Workbooks.Open($FilePath)

#make it visible (just to check what is happening)
$excel.Visible = $true

#print file name
$workbook.sheets.item(1).activate()
$workSheet = $Workbook.Sheets.Item(1)
$WorkSheet.Name

#print cell value
$WorkbookTotal=$workbook.Worksheets.item(1)
$value = $WorkbookTotal.Cells.Item(1,1)
$value.Text 

# First retrieve the website
$result = Invoke-webrequest -Uri "https://www.website.com/$value" -Method Get
$resultTable = @{}

# Get the title
$resultTable.title = $result.ParsedHtml.title

# Return the table we have built as an object
Write-Output New-Object -TypeName PSCustomObject -Property $resultTable

#close excel
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
spps -n Excel

这不是完美的,因为万一所有可能的数字都被取走,循环将永不中断。但是,只要min-max范围足够大,这实际上就不会成为问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。