In this code, I have an insert button that will take in the user's input from the textbox and store it in the database. I know the code works as intended with the other tables that have no Foreign Keys in them, but this one does and I'm not sure how to handle it. Everytime it tries to insert CustomerID, the Foreign Key, I keep getting the following error, System.Data.SqlClient.SqlException: 'The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Orders_Customers". The conflict occurred in database "northwind", table "dbo.Customers", column 'CustomerID'.
Below is the insert button code and an image of the program running.
private void button9_Click(object sender, EventArgs e)
{
Order od = new Order
{
OrderID = int.Parse(ordertxt.Text),
CustomerID = customertxt.Text
};
db.Orders.InsertOnSubmit(od);
try
{
db.SubmitChanges();
}
catch (Exception)
{
MessageBox.Show("Invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
db.SubmitChanges();
}
display_order();
Program Running
The value that you are inserting into the CustomerID column does not exist in your Customer table, so it cannot be inserted as a foreign key. You could either add logic to validate the value against the Customer table before inserting, and create a new customer if needed, or alter the column so that it is no longer a foreign key if you do not need it to act as such.
Related
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.
I have the following code in C#:
public int AddSynonymBL(String[] syns, String word, User user)
{
int dismissedCounter = 0;
foreach (var item in syns)
{
BusinessLayerStatus.StatusBL res = this.dataAccess.AddSynonymDA(item.Trim().ToLowerInvariant(), word.Trim().ToLowerInvariant(), user);
if (res == BusinessLayerStatus.StatusBL.SynonymNotAdded)
++dismissedCounter;
}
int numberOfFailures = dismissedCounter;
return numberOfFailures;
}
And the following code is for AddSynonymDA method:
internal BusinessLayerStatus.StatusBL AddSynonymDA(string synonym, string word, User user)
{
try
{
Synonym newSyn = new Synonym()
{
Meaning = synonym
};
//The following if means that the searched word does not exist int the Searched table
if (this.context.Users.Where(a => a.Mail.Equals(user.Mail)).FirstOrDefault().Searcheds.Where(b => b.RealWord.Equals(word)).Count() == validNumberForKeyValues)
{
this.context.Users.Where(a => a.Mail.Equals(user.Mail)).FirstOrDefault().Searcheds.Where(b => b.RealWord.Equals(word)).FirstOrDefault().Synonyms.Add(newSyn);
this.context.SaveChanges();
return BusinessLayerStatus.StatusBL.SynonymAdded;
}
else
return BusinessLayerStatus.StatusBL.SynonymNotAdded;
}
catch (Exception ex)
{
ExceptionAction(ex);
return BusinessLayerStatus.StatusBL.SynonymNotAdded;
}
}
I am using Entity Framework. I have a table which contains an Id, a word column. Both of them together have unique key constraint in the database. My main code is as follows:
public static void Main()
{
EngineEntities context = new EngineEntities();
BusinessLogic bl = new BusinessLogic();
String[] s = new String[] { "java", "DB" };
Console.WriteLine(bl.AddSynonymBL(s, "Java", new User() { Mail = "media" }));
}
When I add a value which does not exist in the table everything is fine but when I add a value which already exists in the table, calling this.context.SaveChanges(); in the AddSynonymDA method, always throws an exception which was for the previous first exception which caused the first exception and nothing is added to database even if they do not exist in the database. Why is that?
I get the following error which shows that Java already exists. The problem is that Java is for the first call, as the second call, I have passed DB not Java.
{"Violation of UNIQUE KEY constraint 'IX_Searched'. Cannot insert duplicate key in object 'dbo.Searched'. The duplicate key value is (java, 2).\r\nThe statement has been terminated."}
I suspect that you have not set a column to be an Identity column in your database
In other words when you are inserting an entity you need a column to be automatically incrementing.
The way I do this is for example using SQL server:
ALTER TABLE [User] DROP COLUMN [ID];
ALTER TABLE [User]
ADD [ID] integer identity not null;
If you do not have an ID column already you do not need the first line.
After this, update your EF model in your project by deleting the User table and right clicking and Updating Model from Database and select the table.
So now when you insert new entries in you EF model, the ID column will be automatically incremented and you won't get an error.
you must initially check whether the item exists or not, since you seem to have a unique constraint, then you should utilize the attributes of reference in your code .
Hi guys i'm trying to modify a piece of data in my database here is the section of code i'm using.
private void btnModifyMember_Click(object sender, EventArgs e)
{
string memberid = txtMemberID.Text;
string lastname = txtLastName.Text;
string firstname = txtFirstName.Text;
string phone = txtPhoneNumber.Text;
string email = txtEmail.Text;
string update = "UPDATE [Club_Member] SET [MemberID]=#memberid,[LastName]=#lastname,[FirstName]=#firstname,[Phone]=#phone,[E_mail]=#email";
OleDbCommand dbCmd = new OleDbCommand(update, dbConn);
dbCmd.Parameters.AddWithValue("#MemberID", memberid);
dbCmd.Parameters.AddWithValue("#LastName", lastname);
dbCmd.Parameters.AddWithValue("#FirstName", firstname);
dbCmd.Parameters.AddWithValue("#Phone", phone);
dbCmd.Parameters.AddWithValue("#E_mail", email);
try
{
dbCmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
So i run debug, i change one of the entries, i hit the modify member button, then i get a messagebox saying "The record cannot be deleted or changed because table 'Property' includes related records" Debug still goes and I don't get any errors.
Thank you.
You tried to perform an operation that would have violated referential integrity rules for related tables. For example, this error occurs if you try to delete or change a record in the "one" table in a one-to-many relationship when there are related records in the "many" table.
If you want to delete or change the record, first delete the related records from the "many" table. and in your case, you must be trying to update the foreign key column, which is referring to some other table's record.
From your code, one can easily assume that your column MemberID in table club_members, must be a foriegn key, referring to Member table's row. This is where you're making mess. you cannot violate the referential integrity by simply deleting/updating the record you want.
I am new to sql. I have added 2 new tables in database. The primary key of first is a foreign key in the other. The type of the keys is integer. Now I want to generate the keys in the code and assign it to new data so that the association between different rows of the tables is right. How do I ensure uniqueness of keys and also get the latest key from the db so that there are no errors while saving.
If I had used guids then I would have assigned a new guid to the primary key and then assigned the same to the foreign key in the other table. Also there are multiple clients and one server which is saving the data.
The data to be inserted in both the tables is decided in the c# code and is not derived from the row inserted in the primary table. Even if get the id in db then also the relation between the rows should be stored in some form from the code because after that it is lost.
The only viable way to do this is to use INT IDENTITY that the SQL Server database offers. Trust me on this one - you don't want to try to do this on your own!
Just use
CREATE TABLE dbo.YourTableOne(ID INT IDENTITY(1,1), ...other columns...)
and be done with it.
Once you insert a row into your first table, you can retrieve the value of the identity column like this:
-- do the insert into the first table
INSERT INTO dbo.YourTableOne(Col1, Col2, ...., ColN)
VALUES (Val1, Val2, ...., ValN)
DECLARE #NewID INT
-- get the newly inserted ID for future use
SELECT #NewID = SCOPE_IDENTITY()
-- insert into the second table, use first table's new ID for your FK column
INSERT INTO dbo.YourTableTwo (FKColumn, ......) VALUES(#NewID, ......)
Update: if you need to insert multiple rows into the first table and capture multiple generated ID values, use the OUTPUT clause:
-- declare a table variable to hold the data
DECLARE #InsertedData TABLE (NewID INT, ...some other columns as needed......)
-- do the insert into the first table
INSERT INTO dbo.YourTableOne(Col1, Col2, ...., ColN)
OUTPUT Inserted.ID, Inserted.Col1, ..., Inserted.ColN INTO #InsertedData(NewID, Col1, ..., ColN)
VALUES (Val1, Val2, ...., ValN)
and then go from there. You can get any values from the newly inserted rows into the temporary table variable, which will then allow you to decide which new ID values to use for which rows for your second table
As #marc_s said using Database managed keys is more viable. But in cases there is no much load on the database, for example because there are few users who work simultanously, I will use another easier method. That's I get the last id, I try to add new record, and if I encountered error for duplicate, I will try again. I limited this to 3 trials for my application and there's a 300 ms timeout between each trial. Dont forget that this approach has serious limitations. In my application, there are very few users, the work load is very low, and the connection is a local one so this will do job well. Perhaps in other applications you need to adjust the delay, and in some cases, the approach might completely fail. Here's the code,
I have two tables, Invoices and Invoices_Items the column which relates them is invoice_id:
byte attempts = 0;
tryagain: //Find last invoice no
OleDbCommand command = new OleDbCommand("SELECT MAX(invoice_id) FROM Invoices"
, myconnection);
int last_invoice_id = 0;
try
{
last_invoice_id = (int)command.ExecuteScalar();
}
catch (InvalidCastException) { };
// text_invoice_number.Text = Convert.ToString(last_invoice_id + 1);
try
{
command = new OleDbCommand(#"INSERT INTO Invoices
(invoice_id,patient_id,visit_id,issue_date,invoice_to,doctor_id,assistant_id)
VALUES(?,?,?,?,?,?,?)",myconnection);
// We use last_invoice_id+1 as primary key
command.Parameters.AddWithValue("#invoice_id",last_invoice_id+1);
// I will add other parameters here (with the exact order in query)
command.ExecuteNonQuery();
}
catch (Exception ex){
attempts++;
if (attempts <= 3) // 3 attempts
{
System.Threading.Thread.Sleep(300); // 300 ms second delay
goto tryagain;
}
else
{
MessageBox.Show("Can not add invoice to database, " + ex.Message, "Unexpected error!"
, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
for (int i = 0; i <= listInvoiceItems.Count-1; i++)
{
command = new OleDbCommand(#"INSERT INTO Invoices_Items
(invoice_id,quantity,product,price,amount,item_type)
VALUES(?,?,?,?,?,?)",myconnection);
// Now we use our stored last_invoice_id+1 as foreign key
command.Parameters.AddWithValue("#invoice_id",last_invoice_id+1);
// Add other Invoice Items parameters here (with the exact order in query)
command.ExecuteNonQuery();
}
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.