You’re on the right track — let’s clarify these points.
Yes, setting Id as Identity is correct. That means SQL Server will automatically generate unique IDs when you insert new customers.
USE MyFullStackDB; -- replace with your database name
GO
CREATE TABLE Customers (
Id INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Region NVARCHAR(50)
);IDENTITY(1,1)→ starts at 1, increments by 1PRIMARY KEY→ ensures uniqueness
You don’t need to do anything else for IDs; the DB will handle it automatically.
To link Orders.CustomerId to Customers.Id, you create a foreign key. This is not just for querying; it enforces referential integrity in the database.
USE MyFullStackDB; -- replace with your database name
GO
CREATE TABLE Orders (
Id INT IDENTITY(1,1) PRIMARY KEY,
CustomerId INT NOT NULL,
Product NVARCHAR(100) NOT NULL,
Amount DECIMAL(10,2) NOT NULL,
Status BIT NOT NULL, -- 1 = Completed, 0 = Pending
CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerId)
REFERENCES Customers(Id)
);CustomerId INT NOT NULL→ must refer to a valid customerFOREIGN KEY (CustomerId) REFERENCES Customers(Id)→ enforces that each order’s customer exists
Note: This is the database-level relationship. In C# EF or other ORMs, you’d define navigation properties to make it easier to query, but in raw SQL this foreign key is enough.
- Make sure to create
Customerstable first, thenOrders. Foreign key constraints require the referenced table to exist. - If you want to allow deletion of a customer and also delete their orders automatically, you can add
ON DELETE CASCADE:
CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerId)
REFERENCES Customers(Id)
ON DELETE CASCADE- Otherwise, SQL Server will prevent deleting a customer if they have orders.
Once the tables are set up:
SELECT o.Id, c.Name AS CustomerName, o.Product, o.Amount, o.Status
FROM Orders o
JOIN Customers c ON o.CustomerId = c.Id;- This JOIN shows you the customer’s name alongside each order.
- No ORM needed for this — it’s standard SQL.