LINQ to SQL: Get records from two DB's that are on different servers

夙愿已清 提交于 2019-12-22 19:07:02

问题


I need to fetch records from tables, that are in two diff. databases in two different SQL Servers.

For Instance. Sales DB on server1 and Purchase DB on server2. Both Sales and Purchase DB's have some set of tables say table1 in Sales DB and table2 in Purchase DB. Now, I need to get records from table1 and table2 that are having some common records by joining them.

Using T-SQL i can do it by linking the servers and then quering them.

Please suggest, how can i do it using LINQ to SQL as am'nt aware of it.

Thanks.


回答1:


There are (at least) two possible solutions for this.

You could define a stored procedure that does the cross-database query with which you are already familiar. Add the stored procedure as a method on your data context.

Or, you could define a data context for each database, then select the combination in Linq. Something like:

var table1records = from rec1 in context1.Table1
                    select rec1;

var table2records = from rec2 in context2.Table2
                    select rec2;

var combined = from rec1 in table1records
               join rec2 in table2records on rec1.idColumn equals rec2.idColumn
               select new
               {
                 Rec1 = rec1,
                 Rec2 = rec2
               };



回答2:


You can create a View in DB1 that references table2 on DB2.



来源:https://stackoverflow.com/questions/2691890/linq-to-sql-get-records-from-two-dbs-that-are-on-different-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!