简体   繁体   中英

LINQ to SQL Stored procedure Insert

Hi I have the following stored procedure:

create procedure dbo.AddNewUser
(
    @uName nvarchar(20),
    @pass nvarchar(20),
    @fName nvarchar(20),
    @lName nvarchar(20)
)
AS
    insert into [Users] (Username, Password, Firstname, Lastname)
    values (@uName, @pass, @fName, @lName)

This is the code for my table:

CREATE TABLE [dbo].[Users] (
    [Id]        INT        IDENTITY (1, 1) NOT NULL,
    [Username]  NCHAR (20) NOT NULL,
    [Password]  NCHAR (20) NOT NULL,
    [Firstname] NCHAR (20) NOT NULL,
    [Lastname]  NCHAR (20) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

My windows forms program currently has 4 textboxes and 1 button. I am trying to insert the text from the textboxes into my database. This is the code from my click event:

DatabaseConnectionDataContext dc = new DatabaseConnectionDataContext();
dc.AddNewUser(tbUsername.Text, tbPassword.Text, tbFirstname.Text, tbLastname.Text);
dc.SubmitChanges();

When I start the program, enter some data in the textboxes and click the button the data from the textboxes is inserted into the table, but when i start the program again and enter some data into the textboxes, the new data is inserted on the first line instead creating a new line and the old data is erased. Anyone can suggest why is this happening?

You are missing the check if user exists, normally you would do that by id.

using (var dc = new DatabaseConnectionDataContext()){
if (dc.Users.Any(o => o.Username== tbUsername.Text && o.Password == tbPassword.Text ...){
...

}else{dc.AddNewUser(tbUsername.Text, tbPassword.Text, tbFirstname.Text, tbLastname.Text);}

dc.SubmitChanges();
}

EDIT: Having read comment from StefanoGermani
Are you running in memory ravenDb by any chance?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM