Linq to Entity中连接两个数据库时要注意的问题
Linq to Entity中连接两个数据库时要注意的问题
今天大学同学问了我一个问题,Linq to Entity中连接两个数据库时,报错“指定的 LINQ 表达式包含对与不同上下文关联的查询的引用。”
研究下却是发现这个问题,下面是我做的测试:
class Program
{
static void Main(string[] args)
{
using(UserDBEntities context=new UserDBEntities() )
{
using (WaterManageEntities client = new WaterManageEntities())
{
var query = from s in context.NewsTypes where s.ID == client.Layers.FirstOrDefault().LayerID select s;
foreach (NewsType type in query)
{
Console.WriteLine(type.NAME);
Console.ReadKey();
}
}
}
}
}
{
static void Main(string[] args)
{
using(UserDBEntities context=new UserDBEntities() )
{
using (WaterManageEntities client = new WaterManageEntities())
{
var query = from s in context.NewsTypes where s.ID == client.Layers.FirstOrDefault().LayerID select s;
foreach (NewsType type in query)
{
Console.WriteLine(type.NAME);
Console.ReadKey();
}
}
}
}
}
上面的代码报错如图:
但是我无意中修改成下面的代码,就可以了。重新定义一个变量,分步骤来查询就可以了
class Program
{
static void Main(string[] args)
{
using(UserDBEntities context=new UserDBEntities() )
{
using (WaterManageEntities client = new WaterManageEntities())
{
int ID=client.Layers.FirstOrDefault().LayerID ;
var query = from s in context.NewsTypes where s.ID ==ID select s;
foreach (NewsType type in query)
{
Console.WriteLine(type.NAME);
Console.ReadKey();
}
}
}
}
}
{
static void Main(string[] args)
{
using(UserDBEntities context=new UserDBEntities() )
{
using (WaterManageEntities client = new WaterManageEntities())
{
int ID=client.Layers.FirstOrDefault().LayerID ;
var query = from s in context.NewsTypes where s.ID ==ID select s;
foreach (NewsType type in query)
{
Console.WriteLine(type.NAME);
Console.ReadKey();
}
}
}
}
}
总结:
这连接两个不同数据库时报上面的错误,我们只需要分步骤查询就可以了,我的猜测是数据源Connection只能允许我们同时只能连接一个数据库。不知道这个理解是否正确,希望有人有更好的解决办法