如果生成的字符串已存在于数据库中,如何重新生成随机字符串 [英] How do I re-generate a random string if generated string already exists the database
问题描述
我想我有一个简单的情况,我似乎无法解决,我希望有人会对此有所了解:
基本上我有生成如下随机数的方法:
p
I think i have a simple situation which i can't seem to solve and i'm hoping someone would shed some light on this:
basically i have a method that is generating a random number like this:
p
Public static string Code()
{
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var c= new char[6];
var random = new Random();
for (int i = 0; i < c.Length; i++)
{
c[i] = characters[random.Next(characters.Length)];
}
var code = new String(c);
return code;
}
我有另一种检查上述方法中生成的代码是否已存在于数据库中的方法。如果代码存在,则重新生成另一个代码。
I have another method that is checking if the generated code in the method above already exists in the database. If the code exists then re - generate another code .
public void SetCode()
{
string _code = Code();
using(var db = new Database())
{
var p = db.Codes.Where(pc => pc.Code.Equals(Code));
if (p.Any())
{
// this is where i'm stuck, if the code exist i'll do i send it back to generate another code?
}
//if code doesn't exist in the db save it....
}
}
如何才能实现这一目标?
谢谢
我尝试过:
看着do while循环和
How can I go ahead and achieve this?
Thank you
What I have tried:
Looked at do while loops and
if (p.Any())
{
// this is where i'm stuck, if the code exist i'll do i send it back to generate another code?
}
//if code doesn't exist in the db save it....
}
}
推荐答案
解决方案A:
1)在表格中为该字段设置唯一约束
2)检查插入失败
3)失败时重新生成。
解决方案B:
)生成随机字符串
2)使用查询在字段中检查它
3)如果存在则重新生成
对于A和B
4)根据需要重复,但是,如果你的随机字符串很短,我可能会限制重试,以防你的表太密集而且它'永远运行'-ish。
解决方案A总体上需要更少的表格里斯。此外,它可以防止其他不太小心的用户因为约束总是生效而搞砸列的唯一性。
Solution A:
1) Set a unique constraint on that field in the table
2) Check for insert failure
3) regenerate upon failure.
Solution B:
1) Generate random string
2) use query to check for it in field
3) regenerate if it exists
For A and B
4) Repeat as necessary, but, if your random strings are short, I'd possibly limit retries in case your table gets too densely populated and it runs 'forever'-ish.
Solution A will, overall, require fewer table queries. Also, it prevents other users who were less careful from screwing up the columns uniqueness because the constraint is always in effect.
如果你必须使用随机字符串,然后我建议的解决方案是:
If you must use randomized strings, then the solution that I would recommend is:
var random = Guid.NewGuid().ToString("N");
>
正如我在评论中提到的,同时 [ ^ ]或do..while [ ^ ]可以解决问题。
As I mentioned in the comments, either a while[^] or a do..while[^] will do the trick.
string code;
using (var db = new Database())
{
do
{
code = Code();
}
while (db.Codes.Any(pc => pc.Code == code))
}
string code = Code();
using (var db = new Database())
{
while (db.Codes.Any(pc => pc.Code == code))
{
code = Code();
}
}
这篇关于如果生成的字符串已存在于数据库中,如何重新生成随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!