SQL Server PK and FK always equal value - c#

I have question, how can i insert a new data into a database that the primary key and foreign key is always equal in value?
ex. i entered my name into Name table and that Name table has PK and FK. every time i insert a new data, the FK was empty. i expect that the value of FK is same as the value of PK even they have different field name.
above is my database relationship. every time i insert new data the EventsID pk(Eventstbl) wont copy to EvnetsID FK(Organizationtbl)

The referential integrity does not work as you described. It better suits functionality of the triggers. The purpose of the PK and foreign key constraint is to prevent insertion of data which is not exist in other table as PK. Therefore, if you want to copy data from Eventstbl to Organizationtbl upon inserting a new record to the former, you need to write a trigger for the insertion event of the Eventstbl. Your PK - FK constraint will work like following, when you insert new record to Organizationtbl, it will check Eventstbl table for the corresponding EventsID. If it does not exist, it will not allow you to insert new record to Organizationtbl. I hope it helps.

Well, you can use a trigger in EventsTbl, an after insert / update trigger. So this trigger could insert / update the other table you need. You can use the INSERTED table to catch the new value of the PK. I hope it helps.

Related

Bulk insert related sets of data with unknown auto-incremented IDs

We are converting database primary keys from GUIDs to auto-incremented INTs. We have data that we parse from text files and put into two C# DataTables Claim and ClaimCharge that we have been using to bulk insert into identically named tables in the database. In the database, ClaimCharge.ClaimID is a foreign key to Claim.ID and several claim charges exist for one claim.
With GUIDs we generated the Claim and ClaimCharge IDs in C#, so bulk inserting was no problem. But with INTs, I don't know what the Claim.ID will be, so I can't assign ClaimCharge.ClaimID. I need some ideas on how this could be accomplished with INTs.
For instance, if the Claim table could be manually locked against inserts, I could:
Bulk insert into alternate tables named ClaimBulkData ClaimChargeBulkData. These tables would still use GUIDs for convenience in keeping the relationship maintained between C# and SQL.
Manually lock the Claim table against inserts (don't know if this is possible) and get the max(ID).
Increment all of the data in ClaimBulkData using MAX(ID).
Associate ClaimChargeBulkData to ClaimBulkData using the newly updated INT
Insert data into real Claim table as a set using IDENTITY_INSERT ON using some kind of exception to the imaginary lock created in step 2.
Release manually created lock against inserts on Claim table (again I don't know if this is possible.
Insert data into real ClaimCharge table.
I want to avoid inserting the data one row at a time in either C# or T-SQL.
Why not just add the new auto-increment column to the master tables -- you will then have both GUID and autoid column so you can fix up the foreign key relationship (one master table at a time)
i.e.,
Assume you have master1 and detail1 and detail1
alter table Master1 add ID int identity(1,1) not null
GO
alter Detail1 add master1ID int null
GO
alter Detail2 add master1ID int null
GO
Then update Detail1 and Detail12 based on joining Master1 on the oldguid key to set the corresponding value of Master1ID for each table
You can then add the foreign keys based on Master1ID to Detail and Detail2
At this point you should have a complete set of data based on both sets of keys, and you can test update views, etc. to make sure they work with the new integer ids
Finally, once all is cool, drop to unneeded GUID foreign key and the Guid columns themselves.
You can always run a database pack once you get everything clean and converted if your intent was to reduce overall disk usage via this restructuring. The point is much of the work is fixups for foreign keys in a process like this.

delete data from table with no primary key using EF database first

I am working on EF database first application and I have encounter the situation where delete records from a table which has no primary key.
I have no control over the database and it is not possible to add any key for the DB table.
What is the best approach I can take?
The best approach is ,you need add a primary key.
Why EF need you add a PK?
Because, PK is a only way to identity the row in the table , if not exists a PK , the table may have many same rows(if have PK,it's different,PK is unique,each row will be different),so if your want to delete or update ,which row is your target? if not exists PK ,EF couldn't know how to identity the row ,so you must have PK in the table.
If you can't add one (may be the DB is from customer, you don't have permission), you can change the mapping XML file between EF and DB,To add a relate PK Element for a unique table column.

Inserting row into table with auto increment value

I got a table PartsMedia where I can insert all the images related to a product .
The table has the columns :
PartsMediaID , auto-increment
PartsNo
MediaLink
MediaDescription
CatalogCode
SortCode
I want to insert a complete row with automatic increment and the PartsNo should be the same as the PartsNo from the PartsMaster table.
The medialink should be the PartsNo + '-2.jpg'
The mediadescription is for example 'image2'
The CatalogCode should be 'catalog'
and the sorting code should be '0'
From The partsMaster table I Just need the PartNo So I can add this to the PartMedia Table.
The PartNo is the foreign key in the PartMedia table.
The following I got so far but no luck
insert into dbo.PartsMedia (PartNo,MediaLink,MediaDescription,CatalogCode, SortCode)
values (dbo.PartsMaster.PartNo, PartsMaster.PartNo+'-2.jpg','image2', 'catalog','0')
I need some help .
Kind regards,
It's unclear to me what you really want.
But if this is MS SQL, and you're trying to override the identity column (which as auto increment), you need to tell Sql Server that you can insert a new value in the identity column:
SET IDENTITY_INSERT tablename ON
YOUR INSERT GOES HERE
SET IDENTITY_INSERT tablename OFF
Your insert statement lacks a select-clause that grabs the correct row(s) from the PartsMaster table.
insert into foo(a, b, c)
select x, y, z from T
(warning: Dev pretending to know anything about databases)
It sounds like you have a data normalization problem. Each entity should have only one ID in your database, and it only makes sense for something like a surrogate key ID (for that table) to be auto-increment.
If you want to refer to the ID of an entity in a different table, you should have a foreign key constraint, and that column shouldn't be auto-increment.
Reason being - what if in the future you want more than one piece of media (image) for a part? Maybe in the future you'll want pics and vids. In these scenarios, you need to support duplicate PartsNo values.

Inserting Rows in Relationship using a Strongly Typed DataSet

I'm using ADO.NET with a strongly typed dataset in C# (.NET 3.5). I want to insert a new row to two tables which are related in an 1:n relation.
The table Attachments holds the primary key part of the relation and the table LicenseAttachments holds the foreign key part.
AttachmentsDataSet.InvoiceRow invoice; // Set to a valid row, also referenced in InvoiceAttachments
AttachmentsDataSet.AttachmentsRow attachment;
attachment = attachmentsDataSet.Attachments.AddAttachmentsRow("Name", "Description");
attachmentsDataSet.InvoiceAttachments.AddInvoiceAttachmentsRow(invoice, attachment);
Of course when I first update the InvoicesAttachments table, I'll get a foreign key violation from the SQL server, so I tried updating the Attachments table first, which will create the rows, but will remove the attachment association in the InvoiceAttachments table. Why?
How do I solve this problem?
On the relation between the tables, ensure that the "Both Relation and Foreign Key Constraint" is selected and "Update Rule" is set to "Cascade". Combined with the "Refresh the data table" option on the adapter, after you insert your parent row, the updated ID will "Cascade" down the relationships, preventing foreign key violations in your dataset. Your child tables will then be ready to properly insert into the database.
Some things to try:
When you configure the tableadapter, did you click on advanced options, and check on "refresh data table" so that it will retrieve the identity column value?
For me sometimes I either forgot to check it, or it didn't save the configuration correctly because I didn't have my table identity increment/seed set for whatever reason. Are you using identity increment on the table?
You might also consider just re-creating the adapters for those two tables.
Usually when I go back over everything I find it was something stupid on my part.
Lastly, you might consider calling update on the Primary table, then manually grab the primary key value and manually set the value when you insert the child record. If that doesn't make sense let me know and I will post code.
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 ProgramUserGroupTableAdapter -> 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 pug.Update(dsUserGroup.ProgramUserGroup);
Read latest values from the ProgramUserGroup 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

Easy way to add an ID column when there is data present

Is there an easy way to add an ID (Identity(1,1) & PK) column to a table that already has data?
I have picked up a project that was freelanced out to a horrible developer that didn't put a PK, index or anything on the tables he made.
Now that I am LINQ-ifying it, I have no PK to insert or update off of.
ALTER TABLE MyTable ADD id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
I'd be tempted to do it in three stages -
Create a new table with all the same
columns, plus you primary key column
(script out the table and then alter
it to add a PK field)
Insert into the new table all of the
values from the old table
Once your happy with it, delete the
old table and rename your new one
with the Primary Key the same as the
old table.
Open up SQL Server Management Studio
Right click the table
Click Modify
Add the Column
Set the Properties ((Is Identity) Yes, Identity Seed 1, Identity Increment 1)
Right click the Column
Click Set Primary Key
Ctrl-S

Categories