Junior — Middle
Have you ever used foreign keys when working with SQL databases?
sobes.tech AI
Answer from AI
Yes, foreign keys are often used to ensure data integrity and establish relationships between tables in relational databases. For example, if you have an Orders table and a Customers table, a foreign key in Orders can reference the primary key in Customers to ensure that each order is linked to an existing customer.
Example of creating a foreign key in SQL:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(100)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
In C# with Entity Framework, foreign keys are usually defined through navigation properties and attributes or Fluent API.