Scalar Insert Query return null - c#

I am using Sybase Server, project connected to DB via DataSet.
I created insert query on my tableAdapter
INSERT INTO DBA.opt_port(port, port_level, prim, kluch_raz, speed, agr_port, port_bad)
VALUES (?, ?, ?, ?, ?, ?, ?)
Query execute mode is set to Scalar, but after calling this query it always return null.
var newId = opt_portTableAdapter.InsertNewPort(int.Parse(textBox1.Text), int.Parse(textBox2.Text),
textBox3.Text, kluch, int.Parse(textBox4.Text), ToNullableInt(textBox5.Text),
ToNullableInt(textBox6.Text))
I also added parameter to query parameters collection, set Direction as ReturnValue and SourceColumn to my primary key, but still null result.
When I manually check new record in my table, it exist and it's pKey is set.
How can I get my primary key after inserting row?
Table creation query is
CREATE TABLE "DBA"."opt_port" (
"port" smallint NOT NULL,
"port_level" smallint NOT NULL DEFAULT 1,
"prim" char(128) NULL,
"n_pp" integer NOT NULL DEFAULT autoincrement,
"kluch_raz" smallint NULL,
"speed" smallint NULL,
"agr_port" smallint NULL,
"port_bad" smallint NULL,
PRIMARY KEY ( "n_pp" )
);

CREATE PROCEDURE [dbo].[Add_opt_port]
( #input1 varchar(50),
#input2 varchar(50),
#id int output
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO DBA.opt_port
(port, port_level)
VALUES (#input1 , #input2)
SET #id=SCOPE_IDENTITY()
RETURN #id
END

Related

Procedure not working because of unresolved reference to object

I'm writing a WPF application where at some point I'm trying to add new row to my database through procedure like below:
CREATE PROCEDURE dbo.InsertStudent
#IdStudent INT,
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Address VARCHAR(50),
#IndexNumber VARCHAR(50),
#IdStudies INT
AS
SET NOCOUNT ON
INSERT INTO [dbo].[apbd.Student]
([IdStudent]
,[FirstName]
,[LastName]
,[Address]
,[IndexNumber]
,[IdStudies])
VALUES
(#IdStudent
,#FirstName
,#LastName
,#Address
,#IndexNumber
,#IdStudies)
but whenever I'm about to use it, I'm getting error:
SQL71502: Procedure: [dbo].[InsertStudent] has an unresolved reference to object [dbo].[apbd.Student].
I was looking for solution but what I've found was only to add reference to database through right click on References and so on, but I do not have this option in my solution explorer.
Maybe I'm looking for it in wrong places but the only options I have after right click are something like this:
Add reference...
Add reference to service...
Add connected/concatenated/accumulative (or however should it be translated) service
Add analyzer...
Manage NuGet packets...
as for the code behind creation of the tables in database:
CREATE SCHEMA apbd;
GO
-- tables
-- Table: Student
CREATE TABLE apbd.Student (
IdStudent int NOT NULL IDENTITY,
FirstName nvarchar(100) NOT NULL,
LastName nvarchar(100) NOT NULL,
Address nvarchar(100) NOT NULL,
IndexNumber nvarchar(50) NOT NULL,
IdStudies int NOT NULL,
CONSTRAINT Student_pk PRIMARY KEY (IdStudent)
);
-- Table: Student_Subject
CREATE TABLE apbd.Student_Subject (
IdStudentSubject int NOT NULL IDENTITY,
IdStudent int NOT NULL,
IdSubject int NOT NULL,
CreatedAt datetime NOT NULL,
CONSTRAINT Student_Subject_pk PRIMARY KEY (IdStudentSubject,IdStudent,IdSubject)
);
-- Table: Studies
CREATE TABLE apbd.Studies (
IdStudies int NOT NULL IDENTITY,
Name nvarchar(100) NOT NULL,
CONSTRAINT Studies_pk PRIMARY KEY (IdStudies)
);
-- Table: Subject
CREATE TABLE apbd.Subject (
IdSubject int NOT NULL IDENTITY,
Name nvarchar(100) NOT NULL,
CONSTRAINT Subject_pk PRIMARY KEY (IdSubject)
);
-- End of file.
A MS SQL Server database, by default, only has a single schema (dbo). You can add schemas to group things for either security or organizational purposes.
In your case, the schema apbd was created and Student was created on that schema not the dbo schema. So, to reference that table, you need to use [apbd].[Student].
I would run the following to determine the actual name and schema of the table:
SELECT
CAST(
MAX(
CASE
WHEN
TABLE_SCHEMA = 'apbd'
AND TABLE_NAME = 'Student'
THEN 1
ELSE 0
END
) AS bit
) [The table is apbd.Student]
,
CAST(
MAX(
CASE
WHEN
TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'apbd.Student'
THEN 1
ELSE 0
END
) AS bit
) [The table is dbo.apbd.Student]
FROM INFORMATION_SCHEMA.TABLES
I'm also wondering if you perhaps need a USE statement at the start of your CREATE script - are you creating the procedure on the right database?
If the table is on a different database you would need to reference the database in your stored procedure, i.e. [DatabaseName].[dbo].[apbd.Student].

How to insert the foreign key into a subtype table in SQL Server

I have a supertype table called Student, and its subtype table called OtherStudents. I am wondering how to write a stored procedure that will insert the foreign key value into OtherStudents table every time a new record with a student type Other is inserted into Student.
Student table:
CREATE TABLE [dbo].[Student]
(
[STUD_ID] [INT] IDENTITY(1000009,1) NOT NULL,
[STUD_NAM] [VARCHAR](30) NOT NULL,
[STUD_EMAIL] [VARCHAR](50) NULL,
[CAMP_NAM] [VARCHAR](50) NULL,
[CAMP_ZIP] [INT] NULL,
[STUD_TYP] [CHAR](5) NOT NULL,
CONSTRAINT [PK_Student]
PRIMARY KEY CLUSTERED ([STUD_ID] ASC)
)
GO
ALTER TABLE [dbo].[Student] WITH CHECK
ADD CONSTRAINT [FK_Student_Campus]
FOREIGN KEY([CAMP_NAM], [CAMP_ZIP]) REFERENCES [dbo].[Campus] ([CAMP_NAM], [CAMP_ZIP])
GO
ALTER TABLE [dbo].[Student] CHECK CONSTRAINT [FK_Student_Campus]
GO
`OtherStudents` table:
CREATE TABLE [dbo].[OtherStudents]
(
[OSTUD_ID] [INT] IDENTITY(1000009,1) NOT NULL,
[STUD_ST] [VARCHAR](30) NULL,
[STUD_APT] [VARCHAR](5) NULL,
[STUD_CITY] [CHAR](6) NULL,
[STUD_STATE] [CHAR](2) NULL,
[STUD_ZIP] [INT] NULL,
[RPT_ATTM] [VARBINARY](4000) NULL,
[RPT_EYESCR] [VARBINARY](4000) NULL,
[DATE_LASTPASS] [DATE] NULL,
[DATE_LASTVSP] [DATE] NULL,
[STUD_ID] [INT] NULL,
CONSTRAINT [PK_OtherStudents]
PRIMARY KEY CLUSTERED ([OSTUD_ID] ASC)
)
GO
ALTER TABLE [dbo].[OtherStudents] WITH CHECK
ADD CONSTRAINT [FK_OtherStudents_Student]
FOREIGN KEY([STUD_ID]) REFERENCES [dbo].[Student] ([STUD_ID])
GO
ALTER TABLE [dbo].[OtherStudents] CHECK CONSTRAINT [FK_OtherStudents_Student]
GO
I wrote two stored procedures:
ALTER PROCEDURE [dbo].[BusPassStudents_Insert]
(#STUD_ST VARCHAR(30),
#STUD_APT VARCHAR(5),
#STUD_CITY CHAR(6),
#STUD_STATE CHAR(2),
#STUD_ZIP INT,
#RPT_ATTM AS VARBINARY(4000) = NULL,
#RPT_EYESCR AS VARBINARY(4000) = NULL,
#DATE_LASTPASS DATE,
#DATE_LASTVSP AS DATE = NULL)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.OtherStudents (STUD_ST, STUD_CITY, STUD_STATE, STUD_ZIP, RPT_ATTM, RPT_EYESCR,DATE_LASTPASS, DATE_LASTVSP)
VALUES (#STUD_ST, #STUD_CITY, #STUD_STATE, #STUD_ZIP, #RPT_ATTM, #RPT_EYESCR, #DATE_LASTPASS, #DATE_LASTVSP)
END
ALTER PROCEDURE [dbo].[Stud_InsertNew]
(#STUD_NAM VARCHAR(30),
#STUD_EMAIL VARCHAR(50),
#CAMP_NAM VARCHAR(50),
#CAMP_ZIP INT,
#STUD_TYP CHAR(5))
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Student(STUD_NAM, STUD_EMAIL, CAMP_NAM, CAMP_ZIP, STUD_TYP)
VALUES (#STUD_NAM, #STUD_EMAIL, #CAMP_NAM, #CAMP_ZIP, #STUD_TYP);
DECLARE #STUD_ID INT
SET #STUD_ID = SCOPE_IDENTITY()
SELECT #STUD_ID
WHERE #STUD_TYP = 'Other'
END
Here is my C# code I have:
int campzip = int.Parse(ddlCamp.SelectedValue.Trim());
int StudentZip = int.Parse(txtStdZip.Text);
DateTime DateLastPass = DateTime.ParseExact(txtDateLastPass.Text, "yyyy-MM-dd", null);
using (var connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("cis-laredoConnectionString")))
{
connection.Open();
var cmd = new SqlCommand("dbo.Stud_InsertNew", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#STUD_NAM", txtStdName.Text);
cmd.Parameters.AddWithValue("#STUD_EMAIL", txtStdEmail.Text);
cmd.Parameters.AddWithValue("#CAMP_NAM", ddlCamp.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#CAMP_ZIP", campzip);
cmd.Parameters.AddWithValue("#STUD_TYP", "Other");
int getStudID = (int) cmd.ExecuteScalar();
cmd.Dispose();
connection.Close();
connection.Open();
var cmd2 = new SqlCommand("BusPassStudents_Insert", connection);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#STUD_ID", getStudID);
cmd2.Parameters.AddWithValue("#STUD_ST", txtStdStreet.Text);
cmd2.Parameters.AddWithValue("#STUD_APT", txtStdApt.Text);
cmd2.Parameters.AddWithValue("#STUD_CITY", txtStdCity.Text);
cmd2.Parameters.AddWithValue("#STUD_STATE", txtStdState.Text);
cmd2.Parameters.AddWithValue("#STUD_ZIP", StudentZip);
cmd2.Parameters.AddWithValue("#RPT_ATTM", fuAttend.FileBytes);
cmd2.Parameters.Add("#DATE_LASTPASS", SqlDbType.Date).Value = DateLastPass;
cmd2.ExecuteNonQuery();
cmd2.Dispose();
connection.Close();
}
I am trying to use ExecuteScalar to retrieve the inserted STUD_ID in Student table and post it back into the OtherStudents table.
I am getting error:
System.InvalidCastException: 'Specified cast is not valid.'
Any help would be appreciated!
You have to select something from your stored procedure to get the scalar value in the C# which is you missed, so in your Stud_InsertNew you can select the STUD_ID and use ExecuteScalar() in C# code as:
int getStudID = (int)cmd.ExecuteScalar();
Changes in stored procedure:
ALTER PROCEDURE [dbo].[Stud_InsertNew]
(#STUD_NAM VARCHAR(30),
#STUD_EMAIL VARCHAR(50),
#CAMP_NAM VARCHAR(50),
#CAMP_ZIP INT,
#STUD_TYP CHAR(5))
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Student(STUD_NAM, STUD_EMAIL, CAMP_NAM, CAMP_ZIP, STUD_TYP)
VALUES (#STUD_NAM, #STUD_EMAIL, #CAMP_NAM, #CAMP_ZIP, #STUD_TYP);
// Need this line which returns the latest inserted Student Id
SELECT TOP 1 [STUD_ID]
FROM dbo.Student
ORDER BY [STUD_ID] DESC
END
After a comment from Mitch Wheat and also found here, that the best way to use SCOPE_IDENTIY() if you want to get the latest inserted records primary key's value, so you just need to change the SELECT statement to this:
DECLARE #STUD_ID INT
SET #STUD_ID = SCOPE_IDENTITY()
SELECT #STUD_ID
This is how I'd like to approach this.
Convert two procedures into a single one by passing all the required parameters.
Make use of the "inserted" table data to get the information that was just Inserted into table A and store the reference in table B.
*(i) You may want to pass the rest of the parameters required to store the data in table B. I haven't included them in the stored procedure.
(ii) I'm trying to insert data into table B if only the check on birthday passes. In your case the predicate/condition will differ.
USE SOMEDB;
CREATE TABLE A
(Id Integer IDENTITY(1,1),
[Name] VARCHAR(20),
[Birthday] DATE
)
create table B
(
B_Id INTEGER IDENTITY(10001,1),
A_Id Integer NULL,
ColumnX VARCHAR(20),
ColumnY varchar(20))
CREATE PROCEDURE [uspInsertIndividualDetails]
(#name varchar(20),
#birthday date
)
AS
BEGIN
CREATE TABLE #tmpXYZ(iD INT,birthday date);
INSERT INTO A([Name],[Birthday])
OUTPUT inserted.Id,inserted.Birthday into #tmpXYZ
select #name, #birthday
IF exists (select 1 from #tmpXYZ where Birthday >'2018-01-01')
begin
INSERT INTO B(A_Id,ColumnX, ColumnY)
SELECT Id,'A Value', 'Some Other Value' FROM #tmpXYZ
end
END
execute [uspInsertIndividualDetails] #name ='John Doe', #birthday = '1972-10-01'
SELECT * FROM a
SELECT * FROM b
execute [uspInsertIndividualDetails] #name ='John DoeJr', #birthday = '2018-10-01'
SELECT * FROM a
SELECT * FROM b
Hope this helps.
You can do this without making database connection twice by making one stored procedure which combines the two stored procedure's input parameters as:
Reformed stored procedure:
ALTER PROCEDURE [dbo].[Stud_InsertNew]
(#STUD_NAM VARCHAR(30),
#STUD_EMAIL VARCHAR(50),
#CAMP_NAM VARCHAR(50),
#CAMP_ZIP INT,
#STUD_TYP CHAR(5),
// Parameters for other student
#STUD_APT VARCHAR(5),
#STUD_CITY CHAR(6),
#STUD_STATE CHAR(2),
#STUD_ZIP INT,
#RPT_ATTM AS VARBINARY(4000) = NULL,
#RPT_EYESCR AS VARBINARY(4000) = NULL,
#DATE_LASTPASS DATE,
#DATE_LASTVSP AS DATE = NULL)
AS
BEGIN
DECLARE #OTHERCONSTANT NVARCHAR(MAX)
SET #OTHERCONSTANT = 'Other' // You can set to a text that coming from C#
SET NOCOUNT ON
INSERT INTO dbo.Student(STUD_NAM, STUD_EMAIL, CAMP_NAM, CAMP_ZIP, STUD_TYP)
VALUES (#STUD_NAM, #STUD_EMAIL, #CAMP_NAM, #CAMP_ZIP, #STUD_TYP);
IF(#STUD_TYP = #OTHERCONSTANT)
BEGIN
// Need this line which returns the latest inserted Student Id
DECLARE #STUD_ID INT = NULL
SET #STUD_ID = SCOPE_IDENTITY()
INSERT INTO dbo.OtherStudents (STUD_ST, STUD_CITY, STUD_STATE, STUD_ZIP, RPT_ATTM, RPT_EYESCR,DATE_LASTPASS, DATE_LASTVSP)
VALUES (#STUD_ST, #STUD_CITY, #STUD_STATE, #STUD_ZIP, #RPT_ATTM, #RPT_EYESCR, #DATE_LASTPASS, #DATE_LASTVSP)
END
END
C# code:
using(var connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("cis-laredoConnectionString"))) {
connection.Open();
var cmd = new SqlCommand("dbo.Stud_InsertNew", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#STUD_NAM", txtStdName.Text);
cmd.Parameters.AddWithValue("#STUD_EMAIL", txtStdEmail.Text);
cmd.Parameters.AddWithValue("#CAMP_NAM", ddlCamp.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#CAMP_ZIP", campzip);
cmd.Parameters.AddWithValue("#STUD_TYP", "Other");
cmd.Parameters.AddWithValue("#STUD_ST", txtStdStreet.Text);
cmd.Parameters.AddWithValue("#STUD_APT", txtStdApt.Text);
cmd.Parameters.AddWithValue("#STUD_CITY", txtStdCity.Text);
cmd.Parameters.AddWithValue("#STUD_STATE", txtStdState.Text);
cmd.Parameters.AddWithValue("#STUD_ZIP", StudentZip);
cmd.Parameters.AddWithValue("#RPT_ATTM", fuAttend.FileBytes);
cmd.Parameters.Add("#DATE_LASTPASS", SqlDbType.Date).Value = DateLastPass;
cmd.ExecuteNonQuery();
cmd.Dispose();
if (connection.State == ConnectionState.Open) {
connection.Close();
}
}

MsSql server:running stored procedure

I have a table
CREATE TABLE [dbo].[DealerInfo](
[DealerName] [nvarchar](100) NULL,
[Address] [nvarchar](100) NULL,
[City] [nvarchar](100) NULL,
[County] [nvarchar](100) NULL,
[Fax] [nvarchar](50) NULL,
[CompanyWebSite] [nvarchar](max) NULL,
[EmailAddress] [nvarchar](100) NULL,
[Currency] [nvarchar](20) NULL,
[LicenceID] [int] NULL,
[TaxRegistration] [int] NULL,
[Phone] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
And a problem, when i try to insert a currency value it reports that it need an integer value
i insert values with a stored procedure
ALTER PROCEDURE [dbo].[DealerInformation]
-- Add the parameters for the stored procedure here
#DealerName nvarchar(100),
#Address nvarchar(100),
#City nvarchar (100),
#County nvarchar (100),
#Phone nvarchar (100),
#Fax nvarchar(50),
#CompanyWebSite nvarchar (100),
#EmailAddress nvarchar(Max),
#Currency nvarchar(20),
#LicenceID int,
#TaxRegistration int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Insert into DealerInfo values (#DealerName, #Address, #City, #County, #Phone, #Fax, #CompanyWebSite,#EmailAddress,#Currency,#LicenceID,#TaxRegistration)
The Currency is supposed to be a string value like USD, CAD, EUR etc
When i execute the stored procedure this is the error i get
Msg 245, Level 16, State 1, Procedure DealerInformation, Line 26 [Batch Start Line 2]
Conversion failed when converting the nvarchar value 'USD' to data type int.
using (SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=CarDealership;Integrated Security=True") )
{
conn.Open();
SqlCommand cmd = new SqlCommand("DealerInformation", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("DealerName", dealership.DealershipName);
cmd.Parameters.AddWithValue("Address", dealership.Address);
cmd.Parameters.AddWithValue("City", dealership.City);
cmd.Parameters.AddWithValue("County", dealership.Country);
cmd.Parameters.AddWithValue("Phone", dealership.Telephone);
cmd.Parameters.AddWithValue("Fax", dealership.Fax);
cmd.Parameters.AddWithValue("CompanyWebSite", dealership.CompanyWebSite);
cmd.Parameters.AddWithValue("EmailAddress", dealership.Email);
cmd.Parameters.AddWithValue("Currency", dealership.Currency); //The currency is string type
cmd.Parameters.AddWithValue("LicenceID", dealership.LicenceID);
cmd.Parameters.AddWithValue("TaxRegistration", dealership.TaxRegistration);
int RowsAffected = cmd.ExecuteNonQuery();
return RowsAffected;
}
You are using an INSERT INTO statement without specifying the fields names.
Thus your parameters should be listed exactly in the same order of your fields names inside the table
As it is now, the database engine is setting the fields with these parameters
[DealerName] = #DealerName,
[Address] = #Address
[City] = #City
[County] = #County
[Fax] = #Phone
[CompanyWebSite] = #Fax
[EmailAddress] = #CompanyWebSite
[Currency] = #EmailAddress,
[LicenceID] = #Currency,
[TaxRegistration] = #LicenceID
[Phone] = #TaxRegistration
As you can see, your LicenceID field (an int) receives the value of the #Currency parameter (a nvarchar).
This is the cause of the error and the fix is to always specify the field names in the INSERT INTO statement and list the parameters in the correct order to set the associated fields.
Insert into DealerInfo
(DealerName, Address, City, County, Fax, CompanyWebSite,
EmailAddress,Currency,LicenceID,TaxRegistration,Phone)
values (#DealerName, #Address, #City, #County, #Fax, #CompanyWebSite,
#EmailAddress,#Currency,#LicenceID,#TaxRegistration, #Phone)
To me, it seems like your table definition and stored procedure code is not in sync. That is your table definition column data type for currency is actually int, but somehow you have changed it in the editor to nvarchar.
To resolve the issue, right click on your table and check the definition of you table (not the code you have in editor window), You will get your answer.
I hope, it will help you.
Thanks

My "data default (getdate())", it doesn't work

I'm trying to insert in my SQL Server table the current date.
My table includes 3 files:
CREATE TABLE [dbo].[MyTable]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Date] DATE
CONSTRAINT [DF_MyTable_Date] DEFAULT (getdate()) NOT NULL,
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([Id] ASC)
)
When a new user wants to register in the system, he has only to insert his name.
In my table, the Id is generated automatically and the date too, but the date shows 01/01/0001 instead of the current day.
Where is the mistake?
if you create a datetime variable in C# like
var today_date = new DateTime();
and do a Console.WriteLine(today_date); u can see it print 0001-01-01
So this is default value of null..
Use DBNull.Value to insert a SQL NULL from C# and check the result
(Your_Date_Column) Make it Null / Not Null and give default value GetDate() but still it will not work. You have to create a trigger like this,
CREATE TRIGGER [dbo].[Trigger_Date] ON [dbo].[TableName] FOR INSERT AS BEGIN
Declare #Id int
set #Id = (select Id from inserted)
Update [dbo].[TableName]
Set Your_Date_Column = GetDate()
Where Id = #Id
END
Functions and triggers are not required. Just set a column with type Date or DateTime to NOT NULL DEFAULT CURRENT_TIMESTAMP.
Updated example code from the question:
CREATE TABLE [dbo].[MyTable]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Date] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([Id] ASC)
)

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?

Categories