我有以下Action方法: -
public ActionResult Index(string searchTerm=null, int page = 1)
{
var racks = repository.AllFindRacks(searchTerm).OrderBy(a=>a.Technology.Tag).ToPagedList(page, 5) ;
if (Request.IsAjaxRequest())
{
return PartialView("_RackTable", racks);
}
return View(racks);
}
以下Repository方法: -
public IQueryable<RackJoin> AllFindRacks(string q)
{
List<RackJoin> rakjoin = new List<RackJoin>();
var result = from rack in tms.TMSRacks
.Include(rack => rack.DataCenter)
.Include(rack => rack.Zone)
.Include(rack => rack.TMSFirewalls)
.Include(rack => rack.TMsRouters)
.Include(rack => rack.TMSServers)
.Include(rack => rack.TMSStorageDevices)
.Include(rack => rack.TMSSwitches)
.Include(rack => rack.Technology)
join resource in entities.Resources
.Include(a => a.ComponentDefinition)
.Include(a => a.ResourceLocation.SiteDefinition.SDOrganization)
.Include(a => a.ResourceLocation.SiteDefinition.AccountDefinition.SDOrganization)
on rack.Technology.IT360ID equals resource.RESOURCEID
where (q == null || rack.Technology.Tag.ToUpper().StartsWith(q.ToUpper()))
select new RackJoin {
Rack = rack,
Resource = resource,
Customer = resource.ResourceLocation.SiteDefinition.AccountDefinition.SDOrganization,
Site = resource.ResourceLocation.SiteDefinition.AccountDefinition.SDOrganization,
Technology = rack.Technology
};
return result;
}
但是当我调用Action方法时,我得到以下异常: -
System.NotSupportedException未被用户代码
处理 HResult = -2146233067 Message =指定的LINQ表达式包含 引用与不同上下文关联的查询 Source = System.Data.Entity StackTrace:
答案 0 :(得分:8)
看起来您正在加入来自两个不同上下文的数据:tms和实体。
这在LINQ中是不可能的,因为它们都有自己的数据库连接和完全独立的模型。
EF无法将其转换为SQL语句。 (据他所知,这些表可能存在于不同的数据库中)
您需要将所有实体移动到单个上下文或分别执行两个查询,然后将它们连接到内存中。 (如果所有表都在同一个数据库中,则使用第一个选项,如果有单独的数据库,则使用第二个选项)