昨天启动我们软件的促销事件后,我们的 SQL Server 数据库遇到了一些奇怪的问题。当用户在我们的网站上注册帐户时会出现此错误。当用户流量较低时,一切似乎都正常并且工作正常,但一旦流量增加到一次约 10 个注册,一切都会下降。一旦它下来,接下来对数据库的每个请求都会抛出错误。修复它的唯一方法是重新启动网站(直到下一次崩溃等)。
这是错误:
Violation of UNIQUE KEY constraint ‘AK_Users_Username’. Cannot insert duplicate key in object ‘dbo.Users’. The duplicate key value is (username). The statement has been terminated.
(即使我们在添加之前检查用户名)
还发生了另一个错误:
New transaction is not allowed because there are other threads running in the session.
这是一段将用户
及其许可证
添加到数据库的代码:
var db = new CBEntities();
var user = db.Users.Add(new User
{
Username = model.Username,
Firstname = model.FirstName,
Lastname = model.LastName,
Email = model.Email,
Password = model.Password,
EmailConfirmed = 0,
Country = model.Country,
EmailSubscribed = model.Newsletter != null && model.Newsletter.Value ? 1 : 0,
Role = "User",
SignUpDate = DateTime.UtcNow
});
db.SaveChanges();
//create a initial trial license for user
var lic = db.Licenses.Add(new License
{
ExpirationDate = DateTime.UtcNow.AddDays(21),
UserID = user.ID,
Key = "",
PackageID = coupon.ID,
Status = (int)LicenseStatus.Active,
Type = (int)LicenseTypes.TRIAL
});
db.SaveChanges();
user.LicenseID = lic.ID;
db.SaveChanges();
站点和数据库在 Azure 托管上运行。我们确实将网站扩展到标准计划,它甚至使用了多个具有 2 核和 3.5 Gb 内存的实例。它没有解决错误。数据库当前具有具有 S2 性能的标准服务层。等级。 (它链接到网站)..
当没有高用户流量时,一切正常!
请帮助我们找到解决方案
最佳答案
您尚未将 DbContext
包含在 using 语句中。它应该像这样处理:
using (var db = new CBEntities()) {
var user = db.Users.Add(new User
{
Username = model.Username,
Firstname = model.FirstName,
Lastname = model.LastName,
Email = model.Email,
Password = model.Password,
EmailConfirmed = 0,
Country = model.Country,
EmailSubscribed = model.Newsletter != null && model.Newsletter.Value ? 1 : 0,
Role = "User",
SignUpDate = DateTime.UtcNow
});
db.SaveChanges();
//create a initial trial license for user
var lic = db.Licenses.Add(new License
{
ExpirationDate = DateTime.UtcNow.AddDays(21),
UserID = user.ID,
Key = "",
PackageID = coupon.ID,
Status = (int)LicenseStatus.Active,
Type = (int)LicenseTypes.TRIAL
});
db.SaveChanges();
user.LicenseID = lic.ID;
db.SaveChanges();
}
处置DbContext
会关闭与数据库的连接。这可以解释为什么不处理 DbContext 会导致连接过多错误。
当您在网站上几乎没有事件时,连接会超时,这解释了为什么在轻负载下不会出现错误。
关于.net - Azure UNIQUE KEY 约束上的 SQL Server 数据库崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834485/