Finding Foreign Key - asp.net

This question was asked to me recently, any suggestions are welcome.
There is a form containing company details of say 5 companies.>> C_ID, C_Name, c_Address. (Stored in Table Company)
Below there is a grid view which displays employee records and has insert functionality. the fields of grid view are say>> E_ID, E_Name, E_Address. (Stored in Table Employee)
Now this employee has to be mapped with one of the 5 companies. But there is no reference available. How to find the Foreign key? How to maintain relationship between the two Tables?

Add a new field in Employees Table named "C_ID" and make it a FK(foreign key) to be mapped in Company table..
after adding the field, right click Employees table click design. On the design right click and click relationship. Add new relationship, click Tables and Columns Specifical, on the dropdown choose Customer table and choose C_ID.

You'll need to add the column to map the relationship, and add the foreign key to enforce referential integrity for this relationship.
If the employee can be linked to only one company at a time:
(e.g. in Sql Server):
ALTER TABLE Employee ADD CompanyID INT;
ALTER TABLE Employee ADD CONSTRAINT FK_Employee_Company
FOREIGN KEY(Company_ID) REFERENCES Company(C_ID);
If the employee can be many to many to a company, e.g. part time, contractor, or tracking a history across multiple companies, then you will need a new junction table between employee and company to model this relationship.

Related

What if a table doesn't have a primary key

I have made a simple relation table. All consist of three tables:
Tables for storing personal data (Table_Person)
Table for storing address data (Table_Address)
Table to store the relationship between Table_Person and Table_Address (Table_PersonAddress).
What I want to ask is can I delete the primary key in Table_PersonAddress so that Table_PersonAddress doesn't have a primary key and all that's left is the personID and addressID?
Below is an example of a database relation that I made:
enter image description here
Assuming you don't have any foreign key constraints setup on the junction table (that is, the third table which just stores relationships between people and their addresses), you could delete a person from the first table, while leaving behind the relationships in the third table. However, just because you could do this, does not mean you would want to. Most of the time, if you remove a person from the first table, you would also want to remove all of his relationships from the third table. One way to do this in SQLite is by adding cascading delete constraints to the third table, when you create it:
CREATE TABLE Table_PersonAddress (
...
CONSTRAINT fk_person
FOREIGN KEY (personID)
REFERENCES Table_Person (ID)
ON DELETE CASCADE
)
You probably would also want to add a similar constraint for the address field in the third table, since removing an address also invalidates all relationships involving that address.
Note that SQLite does not allow a cascading delete constraint to be added to table which already exists. You will have to recreate your tables somehow in order to add these constrains.
You can delete it, but my advice is to set a composite PRIMARY KEY for the 2 columns personID and addressID so each row is guaranteed to be UNIQUE.
PRIMARY KEY (personID, addressID)
and remember that in SQLite you always have the rowid column to use it as an id of the row if needed.
So create the table with this statement:
DROP TABLE IF EXISTS PersonAddress;
CREATE TABLE PersonAddress (
personID INTEGER,
addressID INTEGER,
PRIMARY KEY(personID, addressID),
FOREIGN KEY (personID) REFERENCES Person (personID) ON DELETE CASCADE,
FOREIGN KEY (addressID) REFERENCES Address (addressID) ON DELETE CASCADE
);
One more thing: why did you define personID and addressID as TEXT?
Surely SQLite is not at all strict at data type definitions, but since the columns they reference are INTEGER they also should be INTEGER.

How to insert row into 2 tables with a one-to-one relationship in SQL Server

Suppose I have 2 tables with a one-to-one relation:
tblOrder (orderId, orderName, totalPrice, billId)
tblBill (billId, billAmount, cardNumber)
The orderId in tblOrder and billId in tblBill are the primary key and they are both identity keys. Also billId in the tblOrder is the unique foreign key.
In the front end using Asp.net, I want the customers to enter the tblOrder information first into the database, then I want them to enter tblBill information. But I want to automate the process of setting the billId foreign key on the tblOrder. Problem is when multiple users will use the system at same time how can I know which bill will belong to which order?
One solution I thought of was to insert an empty row in tblBill and set that id column value to the tblOrder's billId foreign key. And update the bill information when customer enters the bill information in front end. But it doesn't seem like an optimal solution since one empty row insertion will happen for every purchase.

Keep record even after deleting from application

I have two tables, category (pk) and foreign key table Item(fk).
In item table have itemid, item name,category I'd....and this category I'd is foreign key column with primary table...which is having category I'd, Category name.
And I have relationship between category table as parent and. Item table as child table....category I'd is the relationship between them. When I delete records based on itemid the records should be deleted from the application but maintained at backed level..as I do not want duplicate item...even I have deleted from application.
At Application level I am doing these things with textboxes for and drop down list which should category names.
If I have got you correctly, what you want to do is, maintain the data in the database table even if you delete it from the application interface.
If that is the case, you simply can add a column like 'isDeleted' in both of the tables in the database. In the delete event, just fire the update statement instead of actually deleting the record and set the 'isDeleted' field value to 'True'. At the time of displaying data from the tables, just select the records having 'isDeleted' value equals to 'False'.

Entity Framework: Substituting Primary Columns for Foreign Key Columns

I've created a new ASP.NET website. I've generated an Entity Data Model from my database and have dropped a entitydatasource and gridview onto my page and wired up the gridview to pull from the entitydatasource. Now I get columns like this:
id extension prefix did_flag len ten_id restriction_class_id sfc_id name_display building_id floor room phone_id department_id
In each case where the item is named something_id this reflects a foreign key relationship in the database - and I did choose to have the EDM expose foreign key relationships. I'd like to make it so the gridview pulls in the values for these foreign keys rather than just showing the ID numbers - so, for example, department_id might have a value of "101" right now but it should pull from the department table "Marketing".
I don't remember how I ever made it do this in the first place, but the natural action is to display the values - Dynamic Data handles this automatically, one does not have to tell it to do this.

Unique record in Asp.Net SQL

I asked this question previously but the answers weren't what I was looking for.
I created a table in Asp.net without using code. It contains two columns.
YourUserId and FriendUserId
This is a many to many relationship.
Heres what I want:
There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:
Dave : Greg
Dave : Chris
Greg : Chris
Chris : Greg
is good
Dave : Greg
Dave : Greg
is not good.
I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.
If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.
Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?
I tried controling it with my sql insert statement but that did not work. This is what I tried.
INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])
That didn't work for some reason.
Thank you for your help!
You should create a compound primary key to prevent duplicate rows.
ALTER TABLE FriendRequests
ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)
Or select both columns in table designer and right click to set it as a key.
To prevent self-friendship, you'd create a CHECK constraint:
ALTER TABLE FriendRequests
ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)
You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to UserID <> FriendUserID
You might want to look at this question
Sounds like you need a composite key to make both fields a single key.
I have a better idea. Create a new table. Called FriendRequestRelationships. Have the following columns
FriendRelationshipId (PRIMARY KEY)
UserId_1 (FOREIGN KEY CONSTRAINT)
UserId_2 (FOREIGN KEY CONSTRAINT)
Put a unique constraint to only allow one relationship wit UserId_1 and UserId_2. This table now serves as your many-to-many relationship harness.
Create a scalar function that can return the FriendUserId for a UserId, lets say it's called fn_GetFriendUserIdForUserId
You can now display your relationships by running the following query
SELECT dbo.fn_GetFriendUserIdForUserId(UserId_1) AS 'Friend1',
dbo.fn_GetFriendUserIdForUserId(UserId_2) AS 'Friend2',
FROM FriendRelationshipId

Resources