生成Student_UID后需在SQL Server校验唯一性并分配给新学生
实现Student_UID的数据库唯一性校验(ASP.NET Core + SQL Server)
需求:生成16位Student_UID后,需在SQL Server数据库中校验该UID是否已被使用,未被使用则分配给新学生。现有代码已实现UID生成逻辑,需补充数据库校验部分。
解决方案步骤
- 注入数据库上下文:通过构造函数注入EF Core的DbContext,用于数据库操作
- 循环生成并校验:生成UID后检查数据库,若存在则重新生成,直到获取唯一值
- 优化生成方法:修正生成方法的返回值类型,避免不必要的类型转换
- 数据库约束保障:在Student_UID字段上添加唯一约束,防止并发场景下的重复问题
修改后的完整控制器代码
using Microsoft.AspNetCore.Mvc; using System.Security.Cryptography; using Microsoft.EntityFrameworkCore; namespace SchoolWeb.Controllers { public class StudentController : Controller { // 注入数据库上下文,需提前在Startup/Program.cs中配置 private readonly SchoolDbContext _dbContext; public StudentController(SchoolDbContext dbContext) { _dbContext = dbContext; } public async Task<IActionResult> Registration() { long studentUID; bool isUnique; // 循环生成唯一的Student_UID,直到数据库中不存在 do { using var random = RandomNumberGenerator.Create(); // 替代过时的RNGCryptoServiceProvider studentUID = GenerateStudentUniqueNo(random); // 检查数据库中是否已存在该UID // 假设tbleStudentUID表的StudentUID字段存储已分配的UID isUnique = !await _dbContext.tbleStudentUID .AnyAsync(s => s.StudentUID == studentUID); } while (!isUnique); ViewBag.StudentUID = studentUID; return View(); } // 修正返回值类型为long,避免object类型转换 private long GenerateStudentUniqueNo(RandomNumberGenerator random) { const int noOfDigits = 16; const int maxOddWeight = 7 * 9; const int maxEvenWeight = 15 * 9; long total = 0; for (int i = 0; i < noOfDigits; i++) { int maxWeight = i % 2 == 0 ? maxEvenWeight : maxOddWeight; int digit = GenerateRandomDigit(random, maxWeight); total = total * 10 + digit; } return total; } private int GenerateRandomDigit(RandomNumberGenerator random, int maxWeight) { byte[] buffer = new byte[4]; random.GetBytes(buffer); int value = BitConverter.ToInt32(buffer, 0) & 0x7FFFFFFF; // 仅使用正数 return value % maxWeight / (maxWeight / 10); // 归一化到0-9 } public IActionResult Enqury() { return View(); } public IActionResult Stutas() { return View(); } } // 假设的数据库上下文类,需根据实际项目调整 public class SchoolDbContext : DbContext { public SchoolDbContext(DbContextOptions<SchoolDbContext> options) : base(options) { } public DbSet<tbleStudentUID> tbleStudentUID { get; set; } } // 假设的Student UID实体类,需匹配数据库表结构 public class tbleStudentUID { public long StudentUID { get; set; } // 其他字段... } }
关键注意事项
- 并发安全:建议在数据库的
StudentUID字段上添加唯一约束,即使代码校验通过,也能在数据库层面阻止重复插入 - 过时API替换:
RNGCryptoServiceProvider已过时,改用RandomNumberGenerator.Create()实现安全随机数生成 - 异步操作:使用
async/await执行数据库查询,避免阻塞主线程 - 实体类匹配:确保
SchoolDbContext和tbleStudentUID实体类与实际数据库表结构一致
内容的提问来源于stack exchange,提问作者Afjal Ansari
相关产品推荐
相关产品推荐

