Reputation: 1614
In code first approach, it would look like this:
public class Item
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Package> Packages { get; set; }
}
public class Package
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
It would automatically create junction table, and I could easily access item1.Packages
or package1.Items
. But I have trouble creating these tables in an existing SQL Server database. I am including this database into my project as new ADO.NET item, it then looks like .edmx
How do I make foreign keys in SQL query so relationships between tables would look like described above?
Upvotes: 0
Views: 47
Reputation: 119016
This will create the tables as per the code-first classes you posted:
CREATE TABLE Items
(
Id INT PRIMARY KEY,
Title NVARCHAR(MAX),
)
CREATE TABLE Packages
(
Id INT PRIMARY KEY,
Title NVARCHAR(MAX),
)
CREATE TABLE ItemPackages
(
ItemId INT NOT NULL,
PackageId INT NOT NULL,
FOREIGN KEY (ItemId) REFERENCES Items(Id),
FOREIGN KEY (PackageId) REFERENCES Packages(Id)
)
Upvotes: 1