Problem with Database - Foreign Key always Null (T-SQL) - c#

My problem might be a bit long to describe as the project we are working on is a bit bigger, but i will try to be as precise as i can.
Basically we're developing a web-bases woundmanagement (part of a project for university) where the user can enter wounds and set additional information like size, consistence, upload a picture, choose the location, ... .
All those information should be stored in a database (we're working with MS SQL Studio and Visual Studio 2017) where the user can also retrieve it later to view it on the module.
The problem we are facing now is that if we want to show a wound to a special wound to the user, we can't get the foreign keys to work.
We can filter via the casenumber (which is working) but we can't filter wound information by the ID of the wound (each wound is getting an unique ID) - so if we choose a wound, we still get information about ALL wounds which are stored for the given casenr.
This is our "main-table" where each wound is getting an unique ID which is also an ascending identity column:
[wound_id] INT IDENTITY (1, 1) NOT NULL,
[wound_type] VARCHAR (500) NULL,
[wound_description] VARCHAR (500) NULL,
[decuGrade] INT NULL,
[wound_comments] VARCHAR (500) NULL,
[wound_timeReal] DATETIME NULL,
[wound_timeGiven] DATETIME NULL,
[casenumber] INT NULL,
[username] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([wound_id] ASC)
);
If the user enters the information and clicks "Next", a function is called in code behind which fills the table:
_db.SaveWoundDetails(casenr, woundValue, decu, additional_info, realTime, givenBackDocDate, user);
This leads to our database-class, where we have our queries for the database, in this case:
public void SaveWoundDetails(int casenr, string woundType, int decuGrade, string woundComment, DateTime timeReal, DateTime timeGiven , string user)
{
var table = ConfigurationManager.AppSettings["woundDetailsTable"];
var insertQuery = "INSERT INTO " + table + "(casenumber, wound_type, decuGrade, wound_comments, wound_timeReal, wound_timeGiven, username) VALUES (#casenr, #woundType, #decuGrade, #woundComment, #timeReal, #timeGiven, #user)";
var cmd = new SqlCommand(insertQuery);
cmd.Parameters.AddWithValue("#casenr", casenr);
cmd.Parameters.AddWithValue("#woundType", woundType);
cmd.Parameters.AddWithValue("#decuGrade", decuGrade);
cmd.Parameters.AddWithValue("#woundComment", woundComment);
cmd.Parameters.AddWithValue("#timeReal", timeReal);
cmd.Parameters.AddWithValue("#timeGiven", timeGiven);
cmd.Parameters.AddWithValue("#user", user);
var db = DatabaseController.getDataBaseController();
try
{
var sqlcmd = db.executeSQL(cmd);
}
catch (SqlException e)
{
}
}
The connection etc. is in a Database-handler class which is not relevant at the moment.
Until here it works fine. But now we have a second table for more information about the wound, which is also filled on next click, related to this table:
CREATE TABLE [dbo].[epadoc_mod_wound_progress] (
[progress_id] INT IDENTITY (1, 1) NOT NULL,
[wound_length] INT NULL,
[wound_width] INT NULL,
[wound_depth] INT NULL,
[wound_surrounding] VARCHAR (500) NULL,
[wound_consistence] VARCHAR (500) NULL,
[wound_state] VARCHAR (200) NULL,
[wound_painscale] VARCHAR (MAX) NULL,
[wound_itch] VARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([progress_id] ASC)
With the INSERT-METHOD:
public void SaveWoundProgress(int woundLength, int woundWidth, int woundDepth, string woundSurrounding, string woundConsistence, string woundState, string woundPainScale, string woundItch)
{
var table = ConfigurationManager.AppSettings["woundProgressTable"];
var insertQuery = "INSERT INTO " + table + "(wound_length,wound_width,wound_depth, wound_surrounding, wound_consistence, wound_state, wound_painscale, wound_itch) VALUES (#woundLength, #woundWidth, #woundDepth, #woundSurrounding, #woundConsistence, #woundState, #woundPainScale, #woundItch)";
var cmd = new SqlCommand(insertQuery);
cmd.Parameters.AddWithValue("#woundLength", woundLength);
cmd.Parameters.AddWithValue("#woundWidth", woundWidth);
cmd.Parameters.AddWithValue("#woundDepth", woundDepth);
cmd.Parameters.AddWithValue("#woundSurrounding", woundSurrounding);
cmd.Parameters.AddWithValue("#woundConsistence", woundConsistence);
cmd.Parameters.AddWithValue("#woundState", woundState);
cmd.Parameters.AddWithValue("#woundPainScale", woundPainScale);
cmd.Parameters.AddWithValue("#woundItch", woundItch);
var db = DatabaseController.getDataBaseController();
try
{
var sqlcmd = db.executeSQL(cmd);
}
catch (SqlException e)
{
}
}
And the method
_db.SaveWoundProgress(wound_length, wound_width, wound_depth, woundArea, woundEdge, woundStatus, painStatus, itchStatus);
which is execute right after the method mentioned above.
I know how to create foreign keys between two tables, but everything we tried failed - if we try to execute it with a foreign key set which is NOT NULL, we're getting a null-exception.
Example of what we tried:
CONSTRAINT [FK_epadoc_mod_wound_details] FOREIGN KEY ([wound_id])
REFERENCES [dbo].[epadoc_mod_wound_progress] ([progress_id])
If we set a foreign key like this, it didn't work.
We came to the conclusion that it must be a problem the callstack when the two methods are executed - but we don't know how we can fix it.
Maybe we have to set the foreign key in the INSERT-query as an explicit variable?
What we want to achieve is that the wound_id of the details-table is taken as foreign key the the progress-table so that a wound can be later changed (for example if it heals the user could re-enter the new size etc.) and we can filter by ID to just show ONE wound to the patient and not all wounds at the same time if clicked on a specific wound.
Sadly i'm not the big database expert so i hope that you can follow my explanations :).
Thanks for any help!

Your epadoc_mod_wound_progress needs to include a [wound_id] INT NOT NULL column. This is what your foreign key should be built on so that one wound can have many wound progresses. Then, in your insert statement, you'll insert the wound_id that generates in woundDetail table insert into epadoc_mod_wound_progress.

Tried to add a comment but I don't have 50 reputation.
I assume from what I can see that you are trying to achieve a one to many relationship between the "main table" and the "epadoc_mod_wound_progress" table, is that right ?
If so, you don't seem to have a field in the "epadoc_mod_wound_progress" table that stores the wound_id, how are you trying to create a foreign key if you are not storing the wound_id ?
Suggest the Primary Key of the epadoc_mod_wound_progress table is a concatenated key of wound_id and progress_id, with wound_id also being the foreign key linking to the main table.

In table epadoc_mod_wound_progress there must be a wound_id INT NOT NULL column acting as foreign key.
Also the constraint must be added to the foreign key table, i.e. the table on the n side of the 1 to n relation. Assuming that the name of the main table is epadoc_mod_wound_details (you did not show it):
ALTER TABLE dbo.epadoc_mod_wound_progress
ADD CONSTRAINT FK_progress_details FOREIGN KEY (wound_id)
REFERENCES dbo.epadoc_mod_wound_details (wound_id)
ON DELETE CASCADE
Also, by adding ON DELETE CASCADE the progress of a wound detail will automatically be deleted when you delete the wound detail.

Related

Entity Framework, cannot add new object without specifying primary key

I am trying to use Identity to make the tables autoincrement the key upon insert. It worked nicely when I used a simple SQL query to insert a value.
CREATE TABLE [dbo].[extrak]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[kategorianev] VARCHAR(50) NULL,
[nev] VARCHAR(50) NULL,
[ar] INT NULL,
[szin] VARCHAR(50) NULL,
[tobbszor_hasznalhato] TINYINT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
However when I use C# code to add a value, I get an exception saying that I should set identity_insert on (I suppose this is when I want to specify a primary key, but I might have missed something). I tried setting It on also, but didn't work (right before calling the add method).
extrak extra = new extrak();
extra.kategorianev = categoryname;
extra.nev = name;
extra.ar = price;
extra.szin = color;
extra.tobbszor_hasznalhato = b;
Console.WriteLine("1");
DataBaseHandler.AddNewExtra(extra);
Console.WriteLine("2");
DataBaseHandler.SaveDB();
The exception happens on saving. Do I have to find the new primary key for myself, and insert that way? Or can I make Entity Framework handle It somehow?
My mate got It. I had to update the model in VS to make It work.
After that the code above worked nicely.

SqliteCommand.ExecuteReader() returning no rows

I'm trying to read data from a table in my Sqlite database using the Microsoft.Data.Sqlite classes in a UWP application.
There's a single row in the table, inserted by the same application. I can see the data using a Sqlite database browser, and can copy-paste the SQL query into the database browser, run it, and see the correct result returned.
However, when I run the same query using the code below, no data is returned.
string _query = "SELECT [Source] FROM [Sessions] ORDER BY [MinTimeOffset];";
_SessionList = new List<string>();
using (SqliteCommand _command = new SqliteCommand(_query, _Connection))
{
using (SqliteDataReader _reader = _command.ExecuteReader())
{
while (_reader.Read())
{
_SessionList.Add((string)_reader["Source"]);
}
}
}
The table structure is as follows:
CREATE TABLE Sessions (
[Id] INTEGER PRIMARY KEY AUTOINCREMENT,
[Source] NVARCHAR(255) NOT NULL,
[MinValue] FLOAT NULL,
[MaxValue] FLOAT NULL,
[MinTimeOffset] BIGINT NULL,
[MaxTimeOffset] BIGINT NULL
)
And the data is:
1, "2017-09-17-070007-ELEMNT BOLT BDA2-15-0.fit", NULL, NULL, NULL, NULL
No exceptions are thrown, _reader.Read() returns false the first time it is called, and _reader.HasRows is false, suggesting no data is returned by the query.
I'm sure there's something simple I'm missing here - what could cause this?
Update following comments:
I can use ExecuteScalar() to retrieve data from the same table without a problem, although this is performed as part of a transaction alongside thousands of inserts, so I guess is slightly different. The code for that, which works, is as follows:
_query = "SELECT [Id] FROM Sessions WHERE [Source] = #sessionName LIMIT 1;";
long _sessionId;
_IngestCommand.CommandText = _query;
_IngestCommand.Parameters.Add(new SqliteParameter("#sessionName", sessionName));
_sessionId = (long)_IngestCommand.ExecuteScalar();
Regarding how I connection, the database is either a new database created from scratch via DDL statements, or an existing version created in the same manner. It makes no difference which of those two methods I use. There's only one database file at any time - I'm deleting the folder contents manually before running to be sure I'm not opening any copies or old versions etc, then creating the database programmatically and inserting a bunch of data into it in a transaction, including a record into this table which is successfully retrieved as part of the insert logic, then committing the transaction.
At this point I can browse all of the inserted data in a Sqlite database browser. Then I'm calling the method which includes the ExecuteReader() code shown above and receiving no results. The same connection is used throughout - it's opened in a class constructor and closed in the Dispose() method of that class (I know that's not great design - I'm going to refactor it once I've got this figured out. The connection code is shown below:
var _connSB = new SqliteConnectionStringBuilder
{
Cache = SqliteCacheMode.Private,
DataSource = filename,
Mode = SqliteOpenMode.ReadWriteCreate
};
_Connection = new SqliteConnection(_connSB.ToString());
_Connection.Open();
And the code that builds the database:
string[] _commands = {
"CREATE TABLE IF NOT EXISTS ProjectMetaData ([Id] INTEGER PRIMARY KEY AUTOINCREMENT, [Name] NVARCHAR(100) NOT NULL, [Value] NVARCHAR(255) NOT NULL)",
"CREATE TABLE IF NOT EXISTS Series ([Id] INTEGER PRIMARY KEY AUTOINCREMENT, [Name] NVARCHAR(100) NOT NULL, [Unit] NVARCHAR(48) NOT NULL, [MinValue] FLOAT NULL, [MaxValue] FLOAT NULL, [MinTimeOffset] BIGINT NULL, [MaxTimeOffset] BIGINT FLOAT NULL)",
"CREATE TABLE IF NOT EXISTS Sessions ([Id] INTEGER PRIMARY KEY AUTOINCREMENT, [Source] NVARCHAR(255) NOT NULL, [MinValue] FLOAT NULL, [MaxValue] FLOAT NULL, [MinTimeOffset] BIGINT NULL, [MaxTimeOffset] BIGINT NULL)",
"CREATE TABLE IF NOT EXISTS Data ([Id] INTEGER PRIMARY KEY AUTOINCREMENT, [SeriesId] INT NOT NULL, [SessionId] NOT NULL, [TimeOffset] BIGINT NOT NULL, [Value] FLOAT NOT NULL, [Discounted] BIT NULL)"
};
foreach (string _command in _commands)
{
using (SqliteCommand _dbCommand = new SqliteCommand(_command, _Connection))
{
_dbCommand.ExecuteNonQuery();
}
}

Foreign Key conflict on INSERT statement

I'm developing a WinForm desktop application for users to input employees retirement data, using SQL Server 2008 as DB.
One of the tables that gets part of the user data has a reference to another table whose records were defined at design time, adding a Foreign Key constraint for consistency.
CREATE TABLE tbCongedo (
ID int IDENTITY(0,1) PRIMARY KEY,
ID_ANAGRAFICA int NOT NULL,
ID_TIPOLOGIA int NOT NULL,
DECORRENZA datetime NOT NULL,
PROT_NUM nvarchar(7) NOT NULL,
PROT_DATA datetime NOT NULL
);
CREATE TABLE tbTipologia (
ID int IDENTITY(0,1) PRIMARY KEY,
TIPOLOGIA nvarchar(20)
);
INSERT INTO tbTipologia VALUES ('CONGEDO'), ('POSTICIPO'), ('ANTICIPO'), ('REVOCA'), ('DECESSO')
ALTER TABLE tbCongedo
ADD CONSTRAINT FK_tbCongedo_tbTipologia
FOREIGN KEY (ID_TIPOLOGIA) REFERENCES tbTipologia(ID)
Then, I have this code that should execute the INSERT statement
public int Insert(SqlConnection Connessione)
{
using (SqlCommand Comando = new SqlCommand("INSERT INTO tbCongedo VALUES (#ID_ANAGRAFICA, #PROT_NUM, #PROT_DATA, #DECORRENZA, #ID_TIPOLOGIA); SELECT SCOPE_IDENTITY()", Connessione))
{
Comando.Parameters.AddWithValue("#ID_ANAGRAFICA", ID_ANAGRAFICA);
Comando.Parameters.AddWithValue("#PROT_NUM", PROT_NUM);
Comando.Parameters.AddWithValue("#PROT_DATA", PROT_DATA);
Comando.Parameters.AddWithValue("#DECORRENZA", DECORRENZA);
Comando.Parameters.AddWithValue("#ID_TIPOLOGIA", ID_TIPOLOGIA);
ID = Int32.Parse(Comando.ExecuteScalar().ToString());
}
return ID;
}
but I'm given this SqlException:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tbCongedo_tbTipologia". The conflict occurred in database "Scadenziario_ver4_TEST", table "dbo.tbTipologia", column 'ID'
These are the data that I was trying to get inserted in the table:
ID_ANAGRAFICA = 2
ID_TIPOLOGIA = 0
PROT_DATA = {16/03/2018 00:00:00}
DECORRENZA = {16/03/2018 00:00:00}
PROT_NUM = 123456
Funny thing is that when I try to insert those same data manually through SQL Server Management Studio, I'm given no error at all.
Thanks.-
Try specifying fields: (col_name1, col_name2, ...).
Without that the VALUES may not be applied as how you might hope. Variable names are NOT automagically matched with similarly-named columns.
So like this:
... new SqlCommand
(
"INSERT INTO tbCongedo " +
" (ID_ANAGRAFICA, PROT_NUM, PROT_DATA, DECORRENZA, ID_TIPOLOGIA) "
"VALUES (#ID_ANAGRAFICA, #PROT_NUM, #PROT_DATA, #DECORRENZA, #ID_TIPOLOGIA); " +
"SELECT SCOPE_IDENTITY()", Connessione
)
...
I think the problem isn't in the data but in the INSERT statement itself. You are trying to insert the values to the wrong columns using the wrong order. To solve the issue you should either specify the columns in the INSERT statement or correct the order of the values. In your case the query will try to insert the value of #PROT_NUM in the ID_TIPOLOGIA instead.

How can I get temporal table schema information from DACFx API?

Consider the following TSql code:
CREATE TABLE Employee
(
[EmployeeID] int NOT NULL PRIMARY KEY CLUSTERED
, [Name] nvarchar(100) NOT NULL
, [Position] varchar(100) NOT NULL
, [Department] varchar(100) NOT NULL
, [Address] nvarchar(1024) NOT NULL
, [AnnualSalary] decimal (10,2) NOT NULL
, [ValidFrom] datetime2 (2) GENERATED ALWAYS AS ROW START
, [ValidTo] datetime2 (2) GENERATED ALWAYS AS ROW END
, PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistory));
... and the following C# code using DACFx:
TSqlObject table;
TSqlObject nameColumn;
// picture some code instantiating the two variables above
var primaryKey = table.GetChildren().Single(x => x.ObjectType == ModelSchema.PrimaryKeyConstraint);
var isMax = nameColumn.Object.GetProperty<bool?>(Column.IsMax);
So here we see that I've queried the DACFx API to find out if the column instance is a MAX-kind of column, and to get information on the table's primary key.
Now I would like to know about the temporal setup of the table. I need to know if SYSTEM_VERSIONING is on, and if it is, what is the table that serves as the history table. I also would like to know which fields are used as the row start and end.
How can I know this using DACFx API?
I know this an old question, but I just spent a whole day and finally figured out how can you pull the the SYSTEM_VERSIONING settings. Hopefully this will be helpful for someone else:
TSqlObject table;
// Code initializing the variable
// Get the type of retention. This can be either -1 (if Infinite)
// or one of the value in the TemporalRetentionPeriodUnit enum
var retentionUnit = table.GetProperty<int>(Table.RetentionUnit);
// Get the retention value. If retention is Infinite this will be -1
var retentionValue = table.GetProperty<int>(Table.RetentionValue);
// Get a reference to the history table.
var historyTable = table.GetReferenced(Table.TemporalSystemVersioningHistoryTable);

Exception On Foreign Constraint

I have a table StaffLevelMapping that has a foreign key column, which is a primary key another table AcademicLevel. It raises an exception that the Insert statement conflicted with a foreign key and it has its reference on the foreign key and the table in which it's a primary key. I know this usually happens if the value you are inserting does not exist in it's original table. But this does exist actually. I tried inserting it directly in SQL Server and it worked perfectly. But through my code it doesn't work. What surprises me the most is I used the same insert logic for the rest of my tables and I don't have problems save this one with this very table. Please I need a very quick help on this I have not slept in 2 days because of this error.
Here's my insert code below:
public static StaffLevelMapping AddStafflevel(int staffId, int levelId, bool isEnabled)
{
var context = ObjectContextHelper.CurrentObjectContext;
var staffLevel = context.StaffLevelMappings.CreateObject();
staffLevel.StaffID = staffId;
staffLevel.ID = levelId;
staffLevel.IsEnabled = isEnabled;
context.StaffLevelMappings.AddObject(staffLevel);
context.SaveChanges();
return staffLevel;
}
Many thanks in advance to that special person that can put me out of this misery.

Categories