Reputation: 646
I'm trying to get data from two different database to retrieve data. , However; I get this error.
**The query contains references to items defined on a different data context**
db = context1
db2 = context2
var query = from m in db.Merch
join d in db.Dept on m.merchDept equals d.deptID.ToString()
join p in db2.PROD_SKU on m.pID equals p.pID
join f in db.FOB on d.fobCode equals f.fobID
join w in db.Item on m.merchID equals w.merchID
join i in db.Doc on m.merchID equals i.MerchID
where p.UPC_NBR.ToString() == upc
How would I go about using these two contexts to retrieve this record using linq. Any help would be appreciated.
Upvotes: 1
Views: 8703
Reputation: 84
For a more complicated scenario, you can also execute two LINQ queries and join the results. Here I acquired the history of status updates to sales quotes and joined them with the table in another database that contains the updating users' names, so I could display them in an ItemsControl:
var firstResults = (from qsl in firstContext.QuoteStatusLogs
join qs in firstContext.QuoteStatus
on qsl.QuoteStatusID equals (qs.QuoteStatusID)
where qsl.QuoteID == quoteID
select new
{
HistoryEvent = qsl.UpdateTime,
QuoteStatus = qs.Description,
UserGUID = qsl.EmployeeGUID,
Comment = qsl.Comment
}).ToList();
var finalResults = (from r1 in firstResults
join e in secondContext.Employees
on r1.UserGUID equals (e.UserID)
orderby r1.HistoryEvent descending
select new QuoteStatusHistoryResult
{
HistoryEvent = r1.HistoryEvent,
QuoteStatus = r1.QuoteStatus,
User = e.FirstName + " " + e.LastName,
Comment = r1.Comment
}).ToList();
statusHistory = new ObservableCollection<QuoteStatusHistoryResult>(finalResults);
That first "ToList" call is important, as without it I got an exception saying I was trying to query from two contexts.
Upvotes: 1
Reputation: 15901
Linq2Sql does not support queries on multiple database context. However, your example looks pretty simple - find p.pID by upc and then use the value as an argument in second query. It may look like this:
db = context1
db2 = context2
var upcId = (from p in db2.PROD_SKU
where p.UPC_NBR.ToString() == upc
select p.pID).Single();
var query = from m in db.Merch
join d in db.Dept on m.merchDept equals d.deptID.ToString()
join f in db.FOB on d.fobCode equals f.fobID
join w in db.Item on m.merchID equals w.merchID
join i in db.Doc on m.merchID equals i.MerchID
where m.pID == upcId;
Upvotes: 3
Reputation: 938
The short answer is that you can't... not easily. In order to do a cross-database join, you have to use one Data Context that references both databases.
<Table Name="db.dbo.Merch" Member="Merch">
...
</Table>
<Table Name="db2.dbo.PROD_SKU" Member="PROD_SKU">
...
</Table>
In your DBML, manually change the names of your tables to look something like the above. You also have to make sure that you've set up permissions to allow querying both databases.
Upvotes: 1