Hello Folks,
Today I will tell you how we can use the power of LINQ to perform join on tables from two different database.
Idea is very much similar to the way we perform join on the tables within a single database with little twist.
After dragging the table from first database, try dragging the table from the second database. Visual studio will give warning but ignore it.
I say Ignore it as it will just change the connection string. This should not be a matter of concern as long as both the database are within the same database engine.
And then go to the property of first table and change the source value to fully qualified name i.e. <DatabaseName>.dbo.<TableName>
See the steps described below:
And then right the code to perform join operation.
static void Main(string[] args)
{
CrossDBLinqDataContext crossdbContext = new CrossDBLinqDataContext();
var result = from t1 in crossdbContext.Test1Tables
join t2 in crossdbContext.Test2Tables on t1.Id equals t2.id
select new { t1, t2 };
foreach (var item in result)
{
Console.WriteLine(item.t1.name);
Console.WriteLine(item.t2.name);
}
}
Happy Coding :)
Happy Coding :)


Great Post! I've been struggling since morning to do cross database join using LINQ to SQL...You've made my day! Thanks a lot!
ReplyDeleteReally great post. I was wondering if this was possible. I am going to test it.
ReplyDeleteThanks
Is not working
ReplyDeleteHello Tudor...
ReplyDeleteCan you please let me know the steps that you are following...this will help me figure out the issue.
Where can you drag & drop this way? I tried the model without success.
ReplyDeleteGreat tip, Thanks!
ReplyDeletei can't buid project.
ReplyDeleteplease help me.
thanks
Hi,
ReplyDeleteI tried this technique, but I'm getting these errors:
Error 18 'Public Property FirstName() As String' has multiple definitions with identical signatures
Ed
How would this work if the databases are named differently on different servers?
ReplyDeleteE.g., you have Test1 and Test2 dbs, but what if they were named TestA and TestB on a different server (with the same schema). Normally I handle this with passing a connection string to the context object but it's not clear how to handle it here...