开发者

How to use unlinked result of linq?

for example I'm trying to get the data from database like:

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;
        }

After this code I cannot transfer the result to some another method because the context doesn't exist more. How could I get the unlinked result independent on the context? Thanks


Materialize the query by calling ToList() on the result. This will run the query and convert the results to a List of the object. Since List<T> implement IEnumerable<T>, this should still work if you've declared your variable as 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 (to SQL) works by building up an Expression tree that represents the query. Until the query is actually enumerated (or explicitly materialized by calling a method like ToList()), the query hasn't been performed. You need to make sure that the query is performed before the context is disposed. The quickest way to do that, given the code you show, is calling ToList(). You could, perhaps, also just extend the context scope to cover your usage, but if you are supplying the data to a view (web page), that's not likely to be effective. In other contexts, however, it might be possible -- say to just include the enumeration of the query inside the using block of the context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜