campbelt
campbelt

Reputation: 1573

Entity Framework 4: How to get records in many-to-many relationship?

I am trying to do something with Entity Framework that I think is pretty basic, but I am new to EF, and so I need help. I am trying to use EF and LINQ to retrieve records from two tables that are in a many-to-many relationship, as I would in SQL with the following query:

SELECT  p.ProductName, pf.ProductFeatureName, pf.ProductFeatureDescription, pf.ProductFeatureActive 
FROM    ProductFeature pf
JOIN    ProductProductFeature ppf ON
    pf.ProductFeatureID = ppf.ProductFeatureID
JOIN    Product p ON
    ppf.ProductID = p.ProductID

One table is Products and the other is ProductFeatures, and their definitions, as well as the definition for an associative table, are as follows:

TABLE Product (
    ProductID INT PRIMARY KEY IDENTITY(1,1),
    ProductCategoryID INT, -- FK to ProductCategory 
    ProductName NVARCHAR(255),
    ProductDescription NVARCHAR(MAX),
    ProductImagePath NVARCHAR(1024),
    PricePerMonth DECIMAL(7,2), -- ex 11111.11
    ProductActive BIT NOT NULL DEFAULT(1)
)

TABLE ProductFeature (
    ProductFeatureID INT PRIMARY KEY IDENTITY(1,1),
    ProductFeatureName NVARCHAR(255),
    ProductFeatureSummary NVARCHAR(255),
    ProductFeatureDescription NVARCHAR(MAX),
    ProductFeatureActive BIT NOT NULL DEFAULT(1)
)

-- ProductCategory to Product association table
TABLE ProductProductFeature (
    ProductProductFeature INT PRIMARY KEY IDENTITY(1,1),
    ProductID INT, -- FK to Product 
    ProductFeatureID INT -- FK to ProductFeature
)

How can this be accomplished?

Upvotes: 0

Views: 507

Answers (1)

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

from p in ctx.Products
.Include("ProductProductFeatures")
.Include("ProductProductFeatures.ProductFeatures")
select p;

Upvotes: 1

Related Questions