Sobes.tech
Junior — Middle

How is the link between tables in a database implemented?

sobes.tech AI

Answer from AI

The relationship between tables in a database is implemented using foreign keys. A foreign key is a field (or set of fields) in one table that references the primary key of another table. This ensures data integrity and allows records to be linked between tables.

Example:

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 ORM, such as Entity Framework, relationships are defined through navigation properties and attributes or Fluent API:

public class Customer
{
    public int CustomerID { get; set; }
    public string Name { get; set; }
    public ICollection<Order> Orders { get; set; }
}

public class Order
{
    public int OrderID { get; set; }
    public DateTime OrderDate { get; set; }
    public int CustomerID { get; set; }
    public Customer Customer { get; set; }
}

Thus, a one-to-many relationship is implemented through a foreign key and navigation properties.