[英]Linq query Join objects with different data sources?
我正在嘗試連接兩個對象,第一個是在Helper中定義的(靜態)本地對象,第二個是(Subsonic)數據庫對象。
這是我的存儲庫中令人反感的摘錄,除非另有要求,否則我不會為您帶來模型和助手的煩惱。
公共IQueryable GetData(字符串DataType){
IQueryable<DatabaseObject> datalist = (
from t in db.All<DatabaseObject>()
join e in WebHelpers.LocalList.AsQueryable<LocalObject>()
on t.Type equals e.Type
orderby t.DateOccurred descending
select t
).Where(e => e.Category == TransType);
return datalist;
}
我意識到,通過將該表放入數據庫中,我可以使我的生活輕松1000倍,對於下一個發行版,我可能會這樣做。 但是有沒有辦法實現我想要做的事情? 我認為這是(a)我未按視圖模型預期的IQueryable返回正確的數據類型,或者(b)Subsonic導致了此問題。
恐怕SubSonic不支持這種交叉引用(至少上次我沒有嘗試過)。
您可以通過僅使用SubSonic來從數據庫中檢索必要的數據來解決此問題,然后在常規C#Linq-to-Objects中執行Join:
public IQueryable GetData(string DataType)
{
// Get a list of the types we need
var requiredTypes = WebHelpers.LocalList.Select(l => l.Type)
.Distinct().ToArray();
// Retrieve all the relevant rows from the database
var dbData = db.All<DatabaseObject>()
.Where(d => requiredTypes.Contains(d.Type))
.ToArray();
// Do the join locally
return (
from t in dbData
join e in WebHelpers.LocalList
on t.Type equals e.Type
orderby t.DateOccurred descending
select t
).Where(e => e.Category == TransType);
}
(順便說一句,如果將.Where()
移到orderby
上方,則可能會獲得更好的性能,因為這樣排序的次數就更少了。也許甚至可以將其包含在數據庫查詢中(檢索dbData
查詢)。由於代碼引用了您未在任何地方聲明的TransType
,並且該方法具有在任何地方都未使用的參數DataType
,並且您不一致地使用了t
和e
,因此無法確定,因為您的代碼令人困惑。
我的最終解決方案是重新組織where子句,以確保select僅返回正確的數據類型(IQueryable)。 在不重新組織where子句的情況下,盡管指定了select t ,聯接數據仍然通過對象傳遞。
public IQueryable GetData(string DataType)
{
IQueryable<DatabaseObject> dbData = (
from t in db.All<DatabaseObject>().Where(e => e.Category == TransType)
join e in WebHelpers.LocalList
on t.Type equals e.Type
orderby t.DateOccurred descending
select t
);
return dbData;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.