【问题标题】:Violation of PRIMARY KEY constraint Cannot Insert Duplicate Primary Key违反 PRIMARY KEY 约束不能插入重复的主键
【发布时间】:2014-02-28 05:32:54
【问题描述】:

我正在从控制器以这种方式生成用户 ID

long lastUserId = 0;

var userProfile = from m in db.UserProfiles select m;
userProfile = userProfile.Where(s => s.DbType == "OFFLINE");

foreach (var c in userProfile)
{
   lastUserId = c.UserId;
}

if (lastUserId != 0)
{
   lastUserId = lastUserId + 1;
}
else
{
   lastUserId = 1000001;
}

当任何两个人同时注册并点击控制器时,我得到了违反密钥的错误现在该怎么办?

【问题讨论】:

  • 您可以使用 GUID 代替 long lastUserId
  • 如果可以的话,让数据库来处理。在 SQL Server 中使用 IDENTITY 列或在 Oracle 中使用 SEQUENCE 为每个请求提供唯一值

标签: asp.net-mvc asp.net-mvc-4 primary-key


【解决方案1】:

对 Id 使用 GUID 或通过在数据库中获取 BigInt 来使 ID 字段自动递增,并让数据库来处理。

Guid lastUserId;
var userProfile = from m in db.UserProfiles select m;
userProfile = userProfile.Where(s => s.DbType == "OFFLINE");

foreach (var c in userProfile)
{
   lastUserId = c.UserId;
}

if (your condition)
{
   lastUserId = new Guid();
}

【讨论】:

  • 我不能使用 BigInt,因为我希望根据我的需要构建唯一 ID
  • 然后将 db 列更改为 Unique identifier (Sql Server) 并使用 Guid。
  • 您能否详细说明您因需要无法使用 bigint 的评论?
  • 在 lastMessagesId = c.MessageId 中出现错误;错误:无法将 long 转换为 guid...
  • 您必须将数据库字段更改为数据库中的唯一标识符
【解决方案2】:

我建议在具有IDENTITY 的列上使用主键,因此您无需检查。

if (lastUserId != 0)
{
   lastUserId = lastUserId + 1;
}
else
{
   lastUserId = 1000001;
}

它会自动增加最后一个的值。

您也可以定义 IDENTITY 应该从 XYZ 数字开始并增加 1 或您想要的。

每个数据库都支持 IDENTITY 功能。

【讨论】:

  • 我不能使用 BigInt,因为我希望根据我的需要构建唯一 ID
  • 是的,你可以使用 bigint db 来做同样的事情
【解决方案3】:

如果在代码中生成标识符,则为 Id 使用 GUID

使用你的数据库...如果你必须使用 long 类型,那么标识符字段应该是一个自动递增的主键,它在插入时创建唯一的数值(SQL Server 的 BIGINT 类型值。)

【讨论】:

    【解决方案4】:

    使用

    static long lastUserId = 0;
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      相关资源
      最近更新 更多