48 c# linq datacontext linqpad linq-to-sql
我经常比较不同数据库中表格中的数据.这些数据库没有相同的架构.在TSQL中,我可以使用DB> user>表结构(DB1.dbo.Stores,DB2.dbo.OtherPlaces)引用它们来提取数据以进行比较.我非常喜欢LINQPad的想法,但我似乎无法在同一组语句中轻松地从两个不同的数据上下文中提取数据.
我见过人们建议只是更改连接字符串以将数据从其他源提取到当前架构中,但正如我所提到的,这是不行的.我刚跳过常见问题解答中的一页吗?这对我来说似乎是一个相当常规的程序.
在"简单"的世界中,我希望能够简单地引用LINQPad创建的类型化数据文本.然后我可以简单地说:
DB1DataContext db1 = new DB1DataContext();
DB2DataContext db2 = new DB2DataContext();
从那里开始工作.
Joe*_*ari 63
更新:现在可以在LINQPad中进行跨数据库SQL Server查询(来自LINQPad v4.31,具有LINQPad Premium许可证).要使用此功能,请在将数据库从"架构资源管理器"拖动到查询窗口时按住Control键.
也可以查询链接的服务器(通过调用sp_add_linkedserver 链接的服务器).去做这个:
请记住,您始终可以自己创建另一个上下文.
public FooEntities GetFooContext()
{
var entityBuilder = new EntityConnectionStringBuilder
{
Provider = "Devart.Data.Oracle",
ProviderConnectionString = "User Id=foo;Password=foo;Data Source=Foo.World;Connect Mode=Default;Direct=false",
Metadata = @"D:\FooModel.csdl|D:\FooModel.ssdl|D:\FooModel.msl"
};
return new FooEntities(entityBuilder.ToString());
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以实例化任意数量的上下文来实现不同的 SQL 实例并执行伪跨数据库联接、复制数据等。注意,跨上下文联接是在本地执行的,因此您必须调用 ToList()、ToArray() 等来执行查询在加入之前分别使用各自的数据源。换句话说,如果您将 DB1.TABLE1 中的 10 行与 DB2.TABLE2 中的 20 行“内部”连接,则在 Linq 执行连接并返回相关/相交之前,必须将这两个集合(所有 30 行)拉入本地机器上的内存中设置(每个示例最多 20 行)。
//EF6 context not selected in Linqpad Connection dropdown
var remoteContext = new YourContext();
remoteContext.Database.Connection.ConnectionString = "Server=[SERVER];Database="
+ "[DATABASE];Trusted_Connection=false;User ID=[SQLAUTHUSERID];Password="
+ "[SQLAUTHPASSWORD];Encrypt=True;";
remoteContext.Database.Connection.Open();
var DB1 = new Repository(remoteContext);
//EF6 connection to remote database
var remote = DB1.GetAll<Table1>()
.Where(x=>x.Id==123)
//note...depending on the default Linqpad connection you may get
//"EntityWrapperWithoutRelationships" results for
//results that include a complex type. you can use a Select() projection
//to specify only simple type columns
.Select(x=>new { x.Col1, x.Col1, etc... })
.Take(1)
.ToList().Dump(); // you must execute query by calling ToList(), ToArray(),
// etc before joining
//Linq-to-SQL default connection selected in Linqpad Connection dropdown
Table2.Where(x=>x.Id = 123)
.ToList() // you must execute query by calling ToList(), ToArray(),
// etc before joining
.Join(remote, a=> a.d, b=> (short?)b.Id, (a,b)=>new{b.Col1, b.Col2, a.Col1})
.Dump();
localContext.Database.Connection.Close();
localContext = null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18483 次 |
| 最近记录: |