![](/img/trans.png)
[英]Error: “The specified LINQ expression contains references to queries that are associated with different contexts”
[英]Error: the specified linq expression contains references to queries that are associated with different context
我有這個 linq 查詢,它返回與給定日期內存在的每個 colorwayid 相關的收入,但它拋出 SQLException:
指定的 linq 表達式包含對與不同上下文關聯的查詢的引用
using (var eshaktiDb = new eshaktiEntities())
{
using (var corpDb = new eshakti_corpEntities())
{
var queryResult =
from product in eshaktiDb.Products
join oivs in corpDb.OrderitemvalueSplits on product.ProductId equals oivs.Productid
join order in corpDb.Orders on oivs.Orderid equals order.OrderID
where product.ColorWaysId != null && order.CrDate >= fromDate && order.CrDate <= toDate
group oivs by product.ColorWaysId into g
select new ColorwayReportResponse
{
colorwayId = (int)g.Key,
revenue = (decimal)g.Sum(o => o.ActItemvalue + o.Custom)
};
return queryResult.ToList();
}
}
如何解決這個問題? 有人可以幫助我進行適合的查詢,而且由於查詢涉及兩個不同的數據庫,我怎樣才能得到我想要的結果?
我會將其分成 2 個單獨的查詢,從您的 corpDb 開始:
var queryResult = (select * from corpDb.OrderitemvalueSplits join order in corpDb.Orders on oivs.Orderid equals order.OrderID).ToArray();
然后我會在其他上下文中使用執行相應的連接。
var products = select * from product in eshaktiDb.Products join oivs in queryResult.OrderitemvalueSplits on product.ProductId equals oivs.Productid where product.ColorWaysId != null && order.CrDate >= fromDate && order.CrDate <= toDate
group oivs by product.ColorWaysId into g
select new ColorwayReportResponse
{
colorwayId = (int)g.Key,
revenue = (decimal)g.Sum(o => o.ActItemvalue + o.Custom)
};
我不確定以上內容是否可以在您的代碼中完全正常工作,但通常不允許您加入實體框架中的 2 個單獨的上下文中,但您可以在請求之間傳遞數組和其他值以完成相同的任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.