DataContext across multiple databases

后端 未结 2 450
孤街浪徒
孤街浪徒 2021-01-07 07:18

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

相关标签:
2条回答
  • 2021-01-07 07:26

    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.

    0 讨论(0)
  • 2021-01-07 07:34

    This is going to sound a little crazy, but I just tested it, so try this:

    • Create a custom entity class for the "external" table you want to join to, or use SqlMetal to generate the class;
    • Go to the 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?

    0 讨论(0)
提交回复
热议问题