I'm working on my own asp.net mvc project and i have a little problem with updating my mysql database.
I have a table in my database with the following columns: (account, firstname, lastname, birthday, phonenumber, profilepicture) all of them are varchar columns and the table is called 'usersprofile'.
Here you can see one row in the table.
https://imgur.com/a/86z68Om
Everytime i try to update any column i get a duplicate primary key error for the primary key column 'cause the update command tries to create a new line.
Here you can see my C# code for the update:
https://imgur.com/a/h2uNzSD
It was a little bit more complex but it didn't work so i decided to make it more simpler by changing it so i can test if it works or not. If i'm correct i used the syntax well and i really have no idea why the update method wants to create a new row in my database.
Do u have any idea?
One of my colleague had the same issue, The Id wasn't auto-generated. You could add that to the Id property in your class. (DatabaseGenerated(DatabaseGeneratedOption.Identity)]).
To manually tackle this(Crude) => Specify the previous Id number to be sure it's updated.
But it's certain you're trying to insert into the table.
Related
I am building my insert new record window called "Add New Case' form in C# and the database is in SQL Server 2019.
Please check the screenshot, I want to display the new record ID in the textbox on the form.
My textbox name is: txtVictimID
Table name: Victim
Column name: victim_ID
This is how I did it:
I used the following query : "SELECT max(victim_ID) FROM [GBV_CMS].[dbo].[Victim]"
And once i got the latest ID, i stored it to a variable 'vID' than I added the code:
victim_IDTextBox.Text = (Convert.ToInt32(vID) + 1).ToString();
It works now, but please let me know if my solution is right, or if someone has a better solution to avoid future issues.
And as you can see in the screenshot:
in the same window form, I need to insert additional case details, which is a separate table in SQL Server.
**How do I make sure, I use the correctvictim_ID value from the Victim table in the Case table as a foreign key so it is linked???
For the witness/perpetrator details table, it is 1-N relationship with the Victim table so I need to use the same new value of victim_ID in these two tables.**
I was really not able to find a solution to this online, therefore, I am seeking help here.
Appreciate, if anyone could please help with the code and instructions.
This link helps
Retrieving Identity or Autonumber Values
I am trying to implement a database in one of my project. The table thats giving me a problem is structured as follows.
Table Savegame:
SaveID(autonumber),
Username(Long text),
GameTitle(long text),
Savestate(short number)
I am trying to insert into the table using the following code
cmd.CommantText - "INSERT INTO Savegame(Username,GameTitle,Savestate) Values('"+username+"','"+game+"','1')";
Everytime I run the code I'm told that I cannot leave the SaveID field empty since its NOT NULL.
Any help would be much appreciated.
At least, supply a number for SaveState:
cmd.CommantText - "INSERT INTO Savegame(Username,GameTitle,Savestate) Values('"+username+"','"+game+"',1)";
Also, are you sure, that the other fields are Long Text, not Short Text?
This may or may not be a noob question, so I'm sure it should be solved easily enough.
I'm trying to use a table in a .mdf database for a contacts list programme I'm writing. For the ID for each of the entries I put, I've got an Identity seed of 1000, with in increment of 1. This works fine when I input things directly into the table. The first entry is 1000, the second is 1001 and so on. I put some text boxes onto the form, and dragged each data source from the table onto their respective text box, so that new entries can be added from the form. The first two entries, which I added directly into the table, show up fine on the form, with their ID as I've previously stated. It's when I try to add a new entry using the form and the controls that I've created that problems arise.
When I add a new entry, the Contact ID for the new entry is set to -1, then -2 and so on. Why is this happening, and how can I fix it?
Relevant snips:
First entry is in there and works fine
New entry has an ID of -1 for some reason
It is default value for IDENTITY fields.
As far as you cannot know which will be the value of an IDENTITY fields unless you insert the record, by default it show -1
The best way to avoid it, it now showing this field when you dateset is on INSERT mode.
In fact, if you try to set it value manually, you will get an error.
Make ID field read-only or don't show it altogether. The INSERT sql for your form should not include identity, i.e.
Insert into contacts (name, company, telephone, mobile, email)
Output INSERTED.*
Values (. . . . .)
If you in c# do command.ExecuteReader using above sql, you will get back all values including ID
I'm making a KTV System, and in part of that system I need to have a database where I can add Karaoke Songs, Store, Delete and Access them. I'm using c#, VS2012. Local database for my database, created a table with 5 columns (Code, Title, Artist, Genre, Path).
Set my code to be unique key and primary key, and also auto-incremented w/ default values(1,1)
Path Column is for the path of the video file to be played whenever a songs is chosen.
I didn't program the database functions, just drag and drop the built-in functions from the datasource like this:
Everything works fine, all the basic functions are working as it should be. When adding it produces negative and weird auto-incremented primary key(which is Code Column) but I know it's fine because everytime I re-run it is already correct. Now
And one thing, after I added my Data Connection and Data Source I also add a New data connection, connecting into the database that is located in the bin folder of the project. Because if I wont do that, everytime I refresh the database it will erase the data inside of it. Or everytime I close the project, it deletes the data, and it gets data from the Empty database from the Project folder not from the bin.
PROBLEM:
For example:
I tried to add 6 rows and then deleted them all, I was thinking that whenever I will add new rows the Code Column will start from 1 2 and 3 again but not, 7, 8 and 9. It seems like it is skipping because there are already 6 existing columns but checked the data table in the database, it isn't. The deleted 6 columns are also gone, same as with the data in the form.
-
and something like this also
I want the Code Column to be always sorted, if ever I delete or Add new rows into the local database.
It all depends how you delete your data.
DELETE * FROM ...
will not affect your auto-increment primary key generator. However,
TRUNCATE TABLE ...
will reset the counter to its initial seed.
May I suggest that you don't attempt to control your auto-generated ID (code), but introduce a new column in your query using the ROW_NUMBER() function.
If you want to reset your primary key or code column truncate the table
Truncate Table tableName
Truncate like others have said will work or with DCBB CHECKIDENT:
DBCC CHECKIDENT (TABLENAMEHERE, RESEED, 0)
I use asp.net 4 and DataSets for accessing the database. There are two tables with one-to-one relationship in the database. It means that both tables have the same column as a primary key (say Id), and one of tables has #identity on this column set.
So in general if we want to insert, we insert first into the first table, than insert into the second table with id.table2 = id of the corresponding record in table1.
I can imagine how to achieve this using stored procedure (we would insert into the first table and have id as an out parameter and then insert into the second table using this id, btw all inside one transaction).
But is there a way to do it without using a stored procedure? May be DataSets \ DataAdapters have such functionality built in?
Would appreciate any help.
Today it is so quiet here... Ok if anybody is also looking for such a solution, I've found a way to do it.
So our main problem is to get the id of the newly created record in the first table. If we're able to do that, after that we simply supply it to the next method which creates a corresponding record in the second table.
I used a DataSet Designer in order to enjoy the code autogeneration feature of the VS. Let's call the first table TripSets. In DataSet Designer right click on the TripSetsTableAdapter, then Properties. Expand InsertCommand properties group. Here we need to do two things.
First we add a new parameter into the collection of parameters using the Parameters Collection Editor. Set ParameterName = #TripId, DbType = Int32 (or whatever you need), Direction = Output.
Second we modify the CommandText (using Query Builder for convenience). Add to the end of the command another one after a semicolon like that:
(...);
SELECT #TripId = SCOPE_IDENTITY()
So you will get something like this statement:
INSERT INTO TripSets
(Date, UserId)
VALUES
(#Date,#UserId);
SELECT #TripId = SCOPE_IDENTITY()
Perhaps you will get a parser error warning, but you can just ignore it. Having this configured now we are able to use in our Business logic code as follows:
int tripId;
int result = tripSetsTableAdapter.Insert(tripDate, userId, out tripId);
// Here comes the insert method into the second table
tripSetTripSearchTableAdapter.Insert(tripId, amountPersons);
Probably you will want to synchronize this operations somehow (e.g. using TransactionScope) but it is completely up to you.