According to my question with weird problem specified here how to fix
System.Data.SqlClient.SqlException: String or binary data would be truncated in table
My problem is, that if I am saving new problem into the database, its ID is always set to 0 (I checked this out in debugging), which then throws
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Alert__Problem_I__17F790F9". The conflict occurred in database "SmartOne", table "dbo.Problem", column 'id'
But in SQL Server Management Studio, the ID is set correctly (ID is defined as an Identity column).
Where both I am using is in my question mentioned below. Thanks for any ideas or advice.
Method that saves Problem:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Problem VALUES " +
"(@nameOfAlert, @value, @result, @message_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("@nameOfAlert", element.NameOfAlert));
command.Parameters.Add(new SqlParameter("@value", (int)element.Value));
command.Parameters.Add(new SqlParameter("@result", (int)element.Result));
command.Parameters.Add(new SqlParameter("@message_ID", element.Message_Id));
command.ExecuteNonQuery();
command.CommandText = "Select @@Identity";
}
conn.Close();
}
}
Method that saves an Alert:
public void Save(Alert element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [Alert] VALUES (@message_ID, @date, @email, @AMUser_ID, @Problem_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("@message_ID", element.Id_MimeMessage));
command.Parameters.Add(new SqlParameter("@date", element.Date));
command.Parameters.Add(new SqlParameter("@email", element.Email));
command.Parameters.Add(new SqlParameter("@AMUser_ID", element.User_ID));
command.Parameters.Add(new SqlParameter("@Problem_ID", element.Problem_ID));
command.ExecuteNonQuery();
command.CommandText = "Select @@Identity";
}
conn.Close();
}
}
SQL Scheme
CREATE TABLE [dbo].[Alert](
[id] [int] IDENTITY(1,1) NOT NULL,
[message_ID] [varchar](100) NOT NULL,
[date] [datetime] NOT NULL,
[email] [varchar](50) NOT NULL,
[AMUser_ID] [int] NOT NULL,
[Problem_ID] [int] NOT NULL);
//Where is ID, it means FK ID
CREATE TABLE [dbo].[Problem](
[id] [int] IDENTITY(1,1) NOT NULL,
[nameOfAlert] [varchar](50) NOT NULL,
[Value_ID] [int] NOT NULL,
[Result_ID] [int] NOT NULL,
[message_ID] [varchar](100) NOT NULL);