为什么在插入新记录时不生成GuID

时间:2016-05-03 01:48:04

标签: asp.net sql-server linq

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

一切正常,除非添加新记录,数据库用户ID是未生成的Guid,但是如果我直接在数据库中输入新记录,则会生成新的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)和这是我得到的错误

  

其他信息:违反PRIMARY KEY约束' PK__User__B9BE370FC96CCDEF'。无法在对象' dbo.User'中插入重复的密钥。重复键值为(00000000-0000-0000-0000-000000000000)。

由于

1 个答案:

答案 0 :(得分: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";

}