2011-09-01 91 views
0

我正在尝试使用实体框架,我认为它很基本,但是我对EF很陌生,所以我需要帮助。我试图使用EF和LINQ to检索两个表是在许多一对多关系记录,因为我将与下面的查询SQL:实体框架4:如何获取多对多关系中的记录?

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 

一个表是产品,另一种是产品功能及其定义以及关联表的定义如下:

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 
) 

这怎么实现?

回答

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

谢谢你,Adilson。我会试试这个。另外,出于好奇,是否可以使用lamba-extension方法类型语法编写等效查询? – campbelt

+0

我认为你可以用lambda语法来做所有事情,因为linq只是IQueryable方法的“语法糖”。 –