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
A co-worker found a thread on another site [social.msdn.microsoft.com] that discusses this same issue. One discussed solution was to perform all joins in views in the "primary" database, and expose those views as objects in the application. That will probably work in my situation, since the majority of my data is in one database, and the small number of tables in the other databases are read-only.
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<T>
property there, i.e.:
partial class DatabaseOneDataContext
{
public Table<ExternalTableRow> ExternalTable
{
get { return GetTable<ExternalTableRow>(); }
}
}
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?