Is there a way for me to create only one foreign key in one table that refers to 2 different fields in that same table
example:
table: family
ID | bird | bird_mom | bird_dad
1___X_____2_______3
2____A____4________5
3____B
4____M
5____N
ID is primary and autoincrement and also foreign key for "bird_mom" and "bird_dad" field.
So when I change entries X,A,B,M,N I dont need to change it everywhere, but it will always be recognized by foreign key-ID
Typically, "foreign key" is the name for the child field that points to the parent, so you would have two foreign keys:
CREATE TABLE family (
ID INTEGER PRIMARY KEY,
bird TEXT,
bird_mom INTEGER REFERENCES family(ID),
bird_dad INTEGER REFERENCES family(ID)
)
Related
Im working on database design on Microsoft Sql server management Studio, I have a small problem. A LibraryItem should have a required category tied with a foreign key of CategoryId mapped to Id in the table Category as shown in the picture.
SEE THE IMAGE
SECOND IMAGE
I need help with how I can tie CategoryId(FK) to Id(PK on Category Table). I just dont know how to do it excatly.
You'll need to add the reference to the script that creates the table and add a name to the constraint like so:
CONSTRAINT FK_LibraryItem_Category_CategoryId FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[Category] ([Id])
Note: I've defaulted to the dbo schema. You will need to change that if it's different for the Category table you are creating.
That will create a Foreign Key for your LibraryItem table and link the CategoryId to the respective record in the Category table.
Another thing to note as well: This will throw errors if your value for the FK doesn't match an ID in the Category table.
To ellaborate on the errors:
Let's say you add a CategoryId of 2 to a record in your LibraryItem table but a record with the ID of 2 doesn't exist in your Category table, it will throw an error similar to this:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_LibraryItem_Category_CategoryId". The conflict occurred in database "foo", table "dbo.LibraryItem". The statement has been terminated.
This can be easily solved by ensuring the IDs match in both tables.
I have a SQL Server table MyTable with a primary key set for column A and also unique clustered index set for columns B and C.
After this call:
(new SqlDataAdapter(new SqlCommand($"select top 0 * from MyTable", conn))).FillSchema(theDataTable, SchemaType.Mapped);
the theDataTable has its .PrimaryKey set to columns B and C, not A.
Why is this so?
As I've commented, this is actually covered in the documentation FillSchema(DataTable, SchemaType, IDbCommand, CommandBehavior):
FillSchema also configures the PrimaryKey and Constraints properties
according to the following rules:
If one or more primary key columns are returned by the SelectCommand, they are used as the primary key columns for the
DataTable.
If no primary key columns are returned but unique columns are, the unique columns are used as the primary key if, and only if, all the
unique columns are nonnullable. If any of the columns are nullable, a
UniqueConstraint is added to the ConstraintCollection, but the
PrimaryKey property is not set.
If both primary key columns and unique columns are returned, the primary key columns are used as the primary key columns for the
DataTable.
Note that primary keys and unique constraints are added to the
ConstraintCollection according to the preceding rules, but other
constraint types are not added.
If a unique clustered index is defined on a column or columns in a SQL
Server table and the primary key constraint is defined on a separate
set of columns, then the names of the columns in the clustered index
will be returned. To return the name or names of the primary key
columns, use a query hint with the SELECT statement that specifies the
name of the primary key index. For more information about specifying
query hints, see Query Hint (Transact-SQL).
If you do need to get the Primary Key details from .PrimaryKey then you'll need to use a hint as the documentation suggests. Without the DDL (including indexes) of your table though, we won't be able to tell you what the hint would be.
I have a table called cars and one called roads
Roads: Cars:
Name Road_Id Owner Car_Id
------------------- ---------------------
roade45 1 Hugo 1
roade20 2 Eson 2
roade10 3 Karl 3
I need to create an N:M relation between these (one can can drive on many roads, one road can have many cars).
It is a dumb example, but it needs to be an N:M relation.
I do this relation by creating an other table called cars_roads with these columns
Road_id | Car_id | uniqueValue
My problem is now that I have no idea on how to get the uniqueValue to take form, this value will be used to prevent doubles from occurring, eg. the same car is added to the same road a second time.
My table is created using this code:
CREATE TABLE [dbo].[Tbl_cars_roads]
(
[Road_id] INT NOT NULL,
[car_id] INT NOT NULL,
CONSTRAINT [PK_Tbl_Road_id] FOREIGN KEY ([Road_id]) REFERENCES [dbo].[Tbl_Cars] ([Road_id]),
CONSTRAINT [PK_Tbl_car_id] FOREIGN KEY ([car_id]) REFERENCES [dbo].[Tbl_Roads] ([car_id])
)
How can I add an uniqueValue key and make it work as explained to this code?
This should make unique group you want.
CONSTRAINT [UQ_CarRoads] UNIQUE NONCLUSTERED
(
[Road_id] ASC,
[car_id] ASC
)
Just add the following code after your last constraint:
CONSTRAINT [UK_Road_Car] UNIQUE ([Road_id], [car_id])
I have two tables:
CREATE TABLE Order (
orderId INTEGER IDENTITY NOT NULL,
PRIMARY KEY (orderId)
)
CREATE TABLE OrderAdditionalDetails (
additionalDetailsId INTEGER IDENTITY NOT NULL,
orderId INTEGER NOT NULL,
PRIMARY KEY (additionalDetailsId),
FOREIGN KEY (orderId) REFERENCES Order(orderId)
)
I have a Foreign key (FK_OrderAdditionalDetails_Order) declared on the OrderAdditionalDetails table, on the orderId field. I also have a 'unique' constraint on the orderId field in the OrderAdditionalDetails table. The idea is that each 'order' will have zero or one entries in the 'OrderAdditionalDetails' table.
This all picked up by the entity framework model file, however when I try to create the Navigation property, it only lets me declare a 1 to many relationship. The error I get is as follows:
Running transformation: Multiplicity is not valid in Role 'OrderAdditionalDetails' in relationship 'FK_OrderAdditionalDetails_Order'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *.
I'm really not sure what this means - googling the error did not prove helpful. Can anybody shed some light on what I am doing wrong?
In your OrderAdditionalDetails table, remove the additionalDetailsID column and make the orderID the CLUSTERED PRIMARY KEY. Keep the FOREIGN KEY you already have. That is the right way to implement this.
There is not only no value added by the additionalDetailsId column, it makes things worse by taking more space in the table. The orderID is already a sufficient key; you need no secondary artificial key that is nothing but a surrogate for orderID.
Your Foreign Key must be defined as UNIQUE in order to enforce a One-To-Zero-Or-One relationship.
Maybe try something like this:
CREATE TABLE OrderAdditionalDetails (
additionalDetailsId INTEGER IDENTITY NOT NULL,
orderId INTEGER NOT NULL UNIQUE,
PRIMARY KEY (additionalDetailsId),
FOREIGN KEY (orderId) REFERENCES Order(orderId)
)
See Also: Implementing one-to-zero-or-one relation in SQL Server
I was trying to associate a table with a view of itself plus some other fields. (There is a very good reason for this that has nothing to do with the answer)
What cause the same error was there was more than one key field on the view. Even though I had specified the fields involved in the association it wanted both to be the only key fields for a 1 to 1 to work.
I also set the key field to be Distinct in the view, but I did that before I removed the key attribute of other fields, so it may ,or may not, be necessary.
I have a table in Microsoft SQL Server 2008 R2 called Page with a primary key called ID. I have another table called Navigation with a column PageID. PageID is a unique foreign key reference to the ID column of Page. This creates a one to one relationship between Navigation and Page records.
When generating models from the database, it creates a one to many relationship where a Page contains a list of Navigation records.
Is this simply the Entity Framework detecting that there is a foreign key involved and ignoring the uniqueness of the columns in the database?
The SQL for the PageID column in Navigation is:
[PageID] INTEGER FOREIGN KEY REFERENCES [Page](ID) UNIQUE NOT NULL
The SQL for the ID column in Page is:
[ID] INTEGER PRIMARY KEY IDENTITY(0, 1) NOT NULL
Here is the solution I had originally, which is what Ladislav was mentioning.
The SQL for the PageID column in Navigation was:
[ID] INTEGER PRIMARY KEY FOREIGN KEY REFERENCES [Page](ID) NOT NULL
Entity framework doesn't support unique keys yet so this information is really ignored and one to many relation is mapped. The only way to use one to one relation in EF is through shared primary key (Navigation's ID will be FK to Page's ID).