I have an application that needs to join tables from multiple databases into a single LINQ-to-SQL query. Unfortunately, I have a separate DataContext class setup for each d
This is going to sound a little crazy, but I just tested it, so try this:
TableAttribute, which should say something like [Table(Name="dbo.ExternalTable")], and change it to [Table(Name="DatabaseTwo.dbo.ExternalTable")]Create a partial class with the same name as the "DatabaseOne" DataContext, and add your Table property there, i.e.:
partial class DatabaseOneDataContext
{
public Table ExternalTable
{
get { return GetTable(); }
}
}
And now try running your entire query off of the first DataContext:
DatabaseOneDataContext context = new DatabaseOneDataContext();
var query = from s in context.RealTable
join t in context.ExternalTable
on s.ID equals t.ID
select new { s, t };
Console.WriteLine(query.ToList().Count);
Unbelievably, it works. It's not quite as simple as just using SqlMetal, but you only need to write the partial class once, then you can just run SqlMetal on both databases and change the TableAttribute of any external tables to include the database name.
It's not perfect, but it's 95% there, no?