简体   繁体   English

LINQ to SQL存储过程插入

[英]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. 我的Windows窗体程序当前有4个文本框和1个按钮。 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. 您错过了检查是否存在用户的权限,通常可以通过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 编辑:已阅读来自StefanoGermani的评论
Are you running in memory ravenDb by any chance? 您是否在内存ravenDb中运行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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