2017-06-01 11 views
0

LINQを使用して初めてのデータベースクエリを作成しようとしています。練習のために私はMicrosoftのAdventure Works 2014データベースを使用しています。LINQクエリを最適化することはできますか?

DB Diagram

私の最初の目標の1つは、特定のベンダーの名前のすべての製品のリストを返すDataServiceの静的メソッドを作成することです。私のメソッドが正しいデータを返すように見えますが、それは非常に最適化されていないと思います。どういうわけか改善することはできますか?あなたが使用する必要があります

public static List<Product> GetProductsByVendorName(string vendorName) 
{ 
    AdventureWorksDatabaseClassDataContext dc = new AdventureWorksDatabaseClassDataContext(); 
    int vendorID = dc.Vendors.Where(vendor => vendor.Name == vendorName).Select(vendor => vendor.BusinessEntityID).First(); 

    IEnumerable <ProductVendor> productsVendor = dc.ProductVendors; 
    IEnumerable<int> selectedProductsID = from ProductVendor productVendor in productsVendor 
              where productVendor.BusinessEntityID == vendorID 
              select productVendor.ProductID; 

    IEnumerable<Product> products = dc.Products; 
    IEnumerable<Product> selectedProducts = from Product p in products 
              where selectedProductsID.Contains(p.ProductID) 
              select p; 

    return selectedProducts.ToList(); 
} 
+0

コードで結合を書き込むように見えます。代わりにクエリでそれを書いてください。 – CodeCaster

+4

このコードに関する特定の問題が特定されていないため、この質問をトピックとしてクローズするよう投票しています。リファクタリングに関する質問は、https://codereview.stackexchange.com –

+2

で質問してください。まあ、はい、3つのクエリではなく1つのクエリを使用します。 –

答えて

1

メモリにネットワークおよびロードエンティティを介してデータを転送避けるために、データベース側で合流する:あなたは、ナビゲーションプロパティを適切に設定している場合、このクエリは次のように見ることができることを

from v in dc.Vendors 
join pv in dc.ProductVendors on v.BusinessEntityID equals v.BusinessEntityID 
join p in dc.Products on p.ProductID equals pv.ProductID 
where v.Name == vendorName 
select p 

は注意

dc.Vendors.Where(v => v.Name == vendorName) 
    .SelectMany(v => v.ProductVendors.Select(pv => pv.Product)) 
関連する問題