【问题标题】:Why GuID is not generated when new record is Inserted为什么插入新记录时不生成GuID
【发布时间】:2016-05-03 01:48:04
【问题描述】:

我正在尝试将新记录插入到我的数据库中。

除了添加新记录外,一切正常,不会生成作为 Guid 的数据库用户 ID,但是如果我直接在数据库中输入新记录,则会生成新的 Guid

protected void btnRegister_Click(object sender, EventArgs e)
{
    // Create a new User Object
    User newUser = new User();

    newUser.user_name = txtRegisterUserName.Text;
    newUser.password = txtRegisterPassword.Text;

    // Add the new object to the Users collection.
    userDB.Users.InsertOnSubmit(newUser);

    // Submit the change to the database.
    userDB.SubmitChanges();
        txtRegisterUserName.Text = "";
        txtRegisterPassword.Text = "";
        lblMessage.Text = "Record has been added";
}

这是我的数据库结构

CREATE TABLE [dbo].[User] 
(
    [user_id]   UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [user_name] VARCHAR (50)     NOT NULL,
    [password]  VARCHAR (50)     NOT NULL,

    PRIMARY KEY CLUSTERED ([user_id] ASC)
);

第一次尝试有效并添加了一个新用户,但是使用这样的 Guid (000-00000-000000),当我尝试添加新记录时,数据库只生成相同的 (000-00000-000000) 和这是我得到的错误

附加信息:违反主键约束“PK__User__B9BE370FC96CCDEF”。无法在对象“dbo.User”中插入重复键。重复键值为(00000000-0000-0000-0000-000000000000)。

谢谢

【问题讨论】:

  • 在不知道任何细节的情况下,看起来user_id 在您的User 实例中被定义并创建为000-00000-000000
  • 但是当我尝试生成一个新的 Guid 并将其插入数据库时​​,仍然插入 000-00000-000000。例如,如果我说类似 newUser.user_id = new Guid();我仍然在我的数据库中得到与我的 id 相同的 000-00000-000000
  • new Guid() 与空 Guid 相同。你想做Guid.NewGuid() 来生成一个新的唯一的Guid
  • 刚刚尝试过并得到了同样的错误.. 那么 newid() 在我的数据库中作为默认值有什么意义呢???
  • 打开您的 EDMX 图,选择 user_id 属性并打开属性窗口。确保 StoreGeneratedPattern 设置为身份。

标签: asp.net sql-server linq


【解决方案1】:

我最终要做的是在实例化我的新用户之前生成一个新的 GuID,然后将其设置为我的 user_id ...不确定这是否是正确的方法,但它现在可以工作

protected void btnRegister_Click(object sender, EventArgs e)
{
   // Generating new GuID 
    var guid = Guid.NewGuid();
    // Create a new User Object
    User newUser = new User();
    newUser.user_id = guid;
    newUser.user_name = txtRegisterUserName.Text;
    newUser.password = txtRegisterPassword.Text;


    // Add the new object to the Users collection.
    userDB.Users.InsertOnSubmit(newUser);

    // Submit the change to the database.
    userDB.SubmitChanges();
        txtRegisterUserName.Text = "";
        txtRegisterPassword.Text = "";
        lblMessage.Text = "Record has been added";

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 2017-10-19
    • 2020-02-28
    • 1970-01-01
    • 2012-07-18
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多