The mysteries of software development and networking... RSS 2.0



 Sunday, October 26, 2008

After discovering that the LINQ to SQL Designer will only support tables from a single data source I set out to manually implement a cross database query using two data contexts.

The result is the following query which joins orders in the OrderDB to products in the VideoGameStoreDB.

public List<Order> FindOrders( string typename )

{

    try

    {

        var productdb = new VideoGameStoreDBDataContext();

        var orderdb = new OrderDBDataContext();

 

        var query  = from o in orderdb.Orders

                     join p in productdb.Products on o.ProductID equals p.ProductID

                     where p.ProductType.ProductTypeName.Contains( typename )

                     select o;

 

 

        return query.ToList();

    }

    catch ( Exception exception )

    {

        Trace.WriteLine( exception );

        throw;

    }

}

 

LINQ to SQL is unable to resolve this query, even though both databases sit on the same server. The compiler will however not warn you not to do this, instead a runtime exception with message 'The query contains references to items defined on a different data context.' occurs.

In a scenario like this the only solution appears to be to write a stored procedure which can perform the cross database query and use that stored procedure from a data context.

Sunday, October 26, 2008 5:16:21 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
C# | LINQ
Sunday, October 26, 2008 12:33:44 PM (Eastern Standard Time, UTC-05:00)
Another option is to call ToArray on each query and perform a local join. Even though this is an option, and it should give you the same results, you should probably never use it.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
About
This blog is run by Mark Blomsma.
© Copyright 2009
Develop-One
Sign In
Statistics
Total Posts: 342
This Year: 0
This Month: 0
This Week: 0
Comments: 102
All Content © 2009, Develop-One
DasBlog theme 'Business' created by Christoph De Baene (delarou)