MsSql server:running stored procedure - c#

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

Related

How do I use Dapper to insert a list<myobject> as parameter to a stored procedure

I have a SQL Server table with 10 columns:
CREATE TABLE [bank].[CommonPostingsFromBankFiles]
(
[Id] [INT] IDENTITY(1,1) NOT NULL,
[BankRegistrationNumber] [INT] NOT NULL,
[BankAccountNumber] [BIGINT] NOT NULL,
[BankName] [NVARCHAR](50) NULL,
[BankAccount] [NVARCHAR](50) NULL,
[PostingAmount] [DECIMAL](18, 2) NOT NULL,
[PostingDate] [DATE] NOT NULL,
[Primo] [CHAR](1) NULL,
[PostingText] [NVARCHAR](100) NULL,
[HideThisRecord] [BIT] NULL,
CONSTRAINT [PK_CommonPostingsFromBankFiles]
PRIMARY KEY CLUSTERED ([BankRegistrationNumber] ASC,
[BankAccountNumber] ASC,
[PostingAmount] ASC,
[PostingDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
)
and a stored procedure that takes 7 parameters:
ALTER PROCEDURE [bank].[spInsertCommonPostings]
(#BankRegistrationNumber INT,
#BankAccountNumber BIGINT,
#BankName NVARCHAR(50),
#PostingAmount DECIMAL(18, 2),
#PostingDate DATE,
#Primo CHAR(1),
#PostingText NVARCHAR(100))
AS
BEGIN
IF NOT EXISTS (SELECT *
FROM bank.CommonPostingsFromBankFiles
WHERE BankRegistrationNumber = #BankRegistrationNumber
AND BankAccountNumber = #BankAccountNumber
AND BankName = #BankName
AND PostingAmount = #PostingAmount
AND PostingDate = #PostingDate)
INSERT INTO bank.CommonPostingsFromBankFiles (BankRegistrationNumber, BankAccountNumber,
BankName, PostingAmount,
PostingDate, Primo, PostingText)
VALUES (#BankRegistrationNumber, #BankAccountNumber,
#BankName, #PostingAmount,
#PostingDate, #Primo, #PostingText);
END;
What I want is to use Dapper to write a List<Postings> to the table using the stored procedure.
I have searched and searched but found no example that helped me.
If I do a
connection.Execute(sql: "spMyStoredProc", MyList, commandType: CommandType.StoredProcedure);
I get an error
Procedure or function spMyStoredProc has too many arguments specified
If I replace the name of the stored procedure with the sql from the stored procedure and set CommandType to Text it works as expected.
Could anybody please post me an example showing how to insert my list using my stored procedure.
Thanks,
Steffen
Simplistically, and assuming the names of the properties in your c# object are identical to the names of the parameters in your stored proc, you could:
MyList.ForEach(x => connection.Execute(sql: "spMyStoredProc", x, commandType: CommandType.StoredProcedure));
If the param/props aren't aligned it may be simplest to provide an anonymous type populated with values from x that covers them
MyList.ForEach(x => connection.Execute(
sql: "spMyStoredProc",
new { BankRegistrationNumber = x.BankRN, ... },
commandType: CommandType.StoredProcedure
));
For a list of 10 objects it will invoke the proc 10 times; it's not the fastest way to do it, but I don't think you've stated any particular goals re performance etc.

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();
}
}

Scalar Insert Query return null

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

NLog DatabaseTarget Install not working

Am using NLog 4.2.2 and asp net 5. All my NLog configurations are on code. I need to deploy my project and want to make sure the appropriate SqlServer Table and StoredProcedure are created. I'm using the DatabaseTarget.Install() method like this:
dbTarget.InstallDdlCommands.Clear();
dbTarget.InstallDdlCommands.Add(new DatabaseCommandInfo
{
ConnectionString = connectionString,
CommandType = System.Data.CommandType.Text,
IgnoreFailures = false,
Text = $#"CREATE TABLE [dbo].[{TableName}] (
[ID] [int] IDENTITY(1,1) NOT NULL,
[MachineName] [nvarchar](200) NULL,
[SiteName] [nvarchar](200) NOT NULL,
[Logged] [datetime] NOT NULL,
[Level] [varchar](5) NOT NULL,
[UserName] [nvarchar](200) NULL,
[Message] [nvarchar](max) NOT NULL,
[Logger] [nvarchar](300) NULL,
[Properties] [nvarchar](max) NULL,
[ServerName] [nvarchar](200) NULL,
[Port] [nvarchar](100) NULL,
[Url] [nvarchar](2000) NULL,
[Https] [bit] NULL,
[ServerAddress] [nvarchar](100) NULL,
[RemoteAddress] [nvarchar](100) NULL,
[Callsite] [nvarchar](300) NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];"
});
dbTarget.InstallDdlCommands.Add(new DatabaseCommandInfo
{
ConnectionString = connectionString,
CommandType = System.Data.CommandType.Text,
IgnoreFailures = false,
Text = $#"CREATE PROCEDURE [dbo].[{ProcName}] (
#machineName nvarchar(200),
#siteName nvarchar(200),
#logged datetime,
#level varchar(5),
#userName nvarchar(200),
#message nvarchar(max),
#logger nvarchar(300),
#properties nvarchar(max),
#serverName nvarchar(200),
#port nvarchar(100),
#url nvarchar(2000),
#https bit,
#serverAddress nvarchar(100),
#remoteAddress nvarchar(100),
#callSite nvarchar(300),
#exception nvarchar(max)
) AS
BEGIN
INSERT INTO [dbo].[{TableName}] (
[MachineName],
[SiteName],
[Logged],
[Level],
[UserName],
[Message],
[Logger],
[Properties],
[ServerName],
[Port],
[Url],
[Https],
[ServerAddress],
[RemoteAddress],
[CallSite],
[Exception]
) VALUES (
#machineName,
#siteName,
#logged,
#level,
#userName,
#message,
#logger,
#properties,
#serverName,
#port,
#url,
#https,
#serverAddress,
#remoteAddress,
#callSite,
#exception
);
END"
});
using (var context = new InstallationContext())
{
if (dbTarget.IsInstalled(context) != true)
dbTarget.Install(context);
}
But when I run my code I get this exception
I have seen this question and I think I'm doing what they say but still doesn't work for me. I know the rest of the code to be good as DB logging works just fine once I manually create the Table and StoredProcedure
After a while I opened an issue in github and I got the answer from there. Turns out that, as of now, when you programmatically create a configuration file (as I was) you have to manually call configuration.Install(installationContext) in order for the different Targets to be actually initialized, as a side effect it will also run the Install method of the Targets that have it. So all the above code needs to do is
// Target configuration as is (except for the installation part)
config.AddTarget(dbTarget);
using(var context = new InstallationContext())
{
config.Install(context);
}
if there are more than one target though I think config.Install(context) should be called after all target (or at least most of them) have being added as it initializes all registered targets and runs Install on them.

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