2010-04-05 15 views
0

例如我想从数据库得到一样的数据:如何使用linq的未链接结果?

using (ExplorerDataContext context = new ExplorerDataContext()) 
     { 
      ObjectQuery<Store> stores = context.Store; 
      ObjectQuery<ProductPrice> productPrice = context.ProductPrice; 
      ObjectQuery<Product> products = context.Product; 
      res = 
       from store in stores 
       join pp in productPrice 
       on store equals pp.Store 
       join prod in products 
       on pp.Product equals prod 
       select store; 
     } 

此代码后的结果,因为上下文不存在,我越不能转移到一些其他方法。我怎样才能得到独立于上下文的未链接结果? 谢谢

回答

2

通过对结果调用ToList()来实现查询。这将运行查询并将结果转换为对象的列表。由于List<T>实施了IEnumerable<T>,如果您已将变量声明为IEnumerable<Store>,则此功能仍应起作用。

using (ExplorerDataContext context = new ExplorerDataContext()) 
    { 
     ObjectQuery<Store> stores = context.Store; 
     ObjectQuery<ProductPrice> productPrice = context.ProductPrice; 
     ObjectQuery<Product> products = context.Product; 
     res = 
      (from store in stores 
      join pp in productPrice 
      on store equals pp.Store 
      join prod in products 
      on pp.Product equals prod 
      select store).ToList(); 
    } 

LINQ(对于SQL)通过构建表示查询的表达式树来工作。直到查询实际枚举(或通过调用像ToList()这样的方法显式实现),查询尚未执行。您需要确保在处理上下文之前执行查询。根据您所展示的代码,最快的方法是拨打ToList()。你也许也可以扩展上下文范围来覆盖你的用法,但是如果你将数据提供给一个视图(网页),这可能不会有效。然而,在其他情况下,这可能是可能的 - 比如只在上下文的using块中包含查询的枚举。

+0

哦,它的工作原理!非常感谢 – mimic 2010-04-06 00:42:53