Local Database in C#, Removing and Adding new column - c#

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)

Related

Adding data to SQL tables in C#

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

How to copy an entire database with Entity Framework?

The purpose of this task is to copy my database that contains the default values for all entities into a new created database. This task will be called when the program creates the database for the first time, so the newly created database would be filled with the values from my default value database.
The problem with just copy and paste database is that my default value database has messy primary keys. The value of each entity's primary key are not in order.
What I want is to create new database for the program, with the values copied from another database but with continuous primary key for each entity (1,2,3,4,5 no jumping).
The requirement is that the structure, references from the default value database has to remain the solid. For example when copied that entity A reset to id=1 from 5, then all the references changed to 1 as well.
How can I achieve this? Is there a fast way to do it instead of manually copying each entities? Because it is quite a large database.
Note: The default database context is identical to the newly created database context.
I my self done such a task few months back.There is no automatic way.You must do it manually.I would like to share the steps where I have used.
Step 1 :
I have created a new db (i.e. Migrated) by initialling (delete data and PK Reseed) the old db.After that I have an exact copy of the old db (i.e. schema only.No data)
Here is the script for one table
Use Migrated;
GO
delete from IpOccupantNotes
GO
--To Reseed the PK
DBCC CHECKIDENT ('[IpOccupantNotes]', RESEED, 0)
GO
Step 2 :
After that I have inserted the relevant data from the old db (Legacy in my case) as shown below.
INSERT INTO [Migrated].[dbo].[IpOccupantNotes] (Name, ZipCode)
select a.Name,a.ZipCode from [Legacy].[dbo].[IpOccupantNotes] as a;
GO
Note : If you have any question,feel free to ask.I'll help to you :)

Query on Identity Column on MS SQL DB

I have created table in MS SQL 2008 with one identity column(Start Value - 1 and Increment is also 1) and 4 other columns. I am accessing this DB from C# ASP.NET. Used to push data only for the non identity column. Identity column will auto increment itself.
As of now i am manually querying the column value with the remaining for columns. But I am facing problem if all the other four column values are equal i am not getting the exact value which i am looking for
Now my query is, Is there any why in C# where I can get the value of the newly created identity column whenever new record is created.
Thanks.
You can use
SCOPE_IDENTITY()
Which will returns the primary key value of the recently inserted row
The answer to your question actually lies in SQL Server. You can run:
SELECT ##identity
after your insert to get the last inserted row identity.
http://technet.microsoft.com/en-us/library/aa933167(v=sql.80).aspx
EDIT BASED ON COMMENTS:
Consider using SCOPE_IDENTITY() as referenced here:
http://technet.microsoft.com/en-us/library/aa259185(v=sql.80).aspx
In SQL terms you can output the records back if you wish it. But how you might apply this to C# is up to you. Example:
INSERT INTO TABLE_A (SOMETHING, SOMETHINGELSE, RANDOMVAL3)
OUTPUT inserted.A_ID, inserted.SOMETHING, inserted.SOMETHINGELSE, inserted.RANDOMVAL3
SELECT 'ASD','DOSD', 123
But unless you're using merge, you can't use OUTPUT to print out any values from joining tables from an INSERT. But that's another matter entirely, I think.
Also, it's hardly good practice to bounce this data between the application and the DB all the time, so I'd look to alternatives if possible.

How Can I Programmatically Override the Auto_Increment Value When Inserting Into a DB

I have just started converting an old web application into a new structure.
I have a newly designed supplier table created in a MS SQL Server 2012 DB, which I am in the process of transferring the supplier data from the old DB to.
I have a C# MVC application set-up using the new DB as the data context. At present the application gets the data from the old applications DB, checks it, reformats it where necessary and inserts it into the new database in the desired format.
However as users of the application have got used to the supplier IDs in the old DB, I don't want to change the IDs, however as the id field in the new supplier table is an auto increment, it doesn't copy the ids from the old database. It just simply increments.
Does anybody know of anyway the auto increment can be overridden programmatically in the c# code for the initial import stage of the project. Once the data from the old system has been imported, I would then like to revert back to auto increment.
You can set identity insert on. However, if the users know the keys I've found they start asking to change them. I might consider the old keys as the user identifier and create a new surrogate key they won't ever see.
You can turn off the identity generation on the server temporarily during the bunch of inserts, then turn it on again. Try submitting this query to the server:
SET IDENTITY_INSERT dbo.sometable ON ;
INSERT INTO dbo.sometable (id,.......) VALUES (456,.......) ;
INSERT INTO dbo.sometable (id,.......) VALUES (276,.......) ;
INSERT INTO dbo.sometable (id,.......) VALUES (387,.......) ;
SET IDENTITY_INSERT dbo.sometable OFF ;
It just disables identity creation, then does the inserts (note that the column and value lists do include the id), then restores the default behavior.
In Sql Server, you can set the ID field to non identity. This will make it not auto increment

Inserting data into C# Datasets

I am using C#.Net application in which i created a dataset.Now i want to create a method in which i will enter a record in one table which will return a value ie primary key.Now by using that primary key i have to insert records in 5 tables and i have to use that primary key as a foreign key for this 5 tables using dataset.
You need to tell your parent table's table-adapter to refresh the
data-table after update operation.
This is how you can do that.
Open the properties of ParentTableAdapter -> Default Select Query -> Advnaced options. and Check the option of Refresh the data table. Save the adapter now. Now when you call update on table-adapter, the data-table will be updated [refreshed] after the update operation and will reflect the latest values from database table. if the primary-key or any coloumn is set to auto-increment, the data-table will have those latest value post recent update.
Now you can Call the update as ParentTableAdapterObj.Update(ds.dataTable);
Read latest values from the ParentDataTable(ds.dataTable) coloumns and assign respective values into the child table before update. This will work exactly the way you want.
alt text http://ruchitsurati.net/files/tds1.png
Have you tried temporary key linkage until the DB generates the final key? Works great for me.

Categories

Resources