我正在使用以下代碼根據officeId欄位連接兩個表。它重新調整了 0 條記錄。
IQueryable<Usage> usages = this.context.Usage; usages = usages.Where(usage => usage.OfficeId == officeId); var agencyList = this.context.Agencies.ToList(); var usage = usages.ToList(); var query = usage.Join(agencyList, r => r.OfficeId, a => a.OfficeId, (r, a) => new UsageAgencyApiModel () { Id = r.Id, Product = r.Product, Chain = a.Chain, Name = a.Name }).ToList();
我在機構表中有 1000 多條記錄,在使用表中有 26 條記錄。
我期望有 26 條記錄,其中鏈和名稱列附加到代理表的結果。
它不回傳任何東西。我是 .net 的新手,如果我遺漏了什么,請指導我
編輯
如果我在執行聯接時同時獲得兩個表背景關系,@Tim Schmelter 的解決方案就可以正常作業。但我需要在應用連接之前在使用表頂部添加過濾器
IQueryable<Usage> usages = this.context.Usage;
usages = usages.Where(usage => usage.OfficeId == officeId);
var query = from a in usages
// works with this.context.usages instead of usages
join u in this.context.Agencies on a.OfficeId equals u.OfficeId
select new
{
Id = a.Id,
Product = a.Product,
Chain = u.Chain,
Name = u.Name
};
return query.ToList();
在此附上截圖

如下所示,相同的連接查詢適用于記憶體資料

如果我直接添加記憶體資料源或兩個資料源,兩種方式都可以正常作業。但是如果我在應用連接查詢之前添加過濾器,usages則officeId不起作用
uj5u.com熱心網友回復:
一個問題是您首先將所有內容加載到記憶體中(ToList())。
對于連接,我更喜歡查詢語法,它不那么冗長:
var query = from a in this.context.Agencies
join u in this.context.Usage on a.OfficeId equals u.OfficeId
select new UsageAgencyApiModel()
{
Id = u.Id,
Product = u.Product,
Chain = a.Chain,
Name = a.Name
};
List<UsageAgencyApiModel> resultList = query.ToList();
編輯:您應該能夠Where在Join. 如果您仍然沒有得到記錄,則沒有匹配:
var query = from a in this.context.Agencies
join u in this.context.Usage on a.OfficeId equals u.OfficeId
where u.OfficeId == officeId
select new UsageAgencyApiModel{ ... };
uj5u.com熱心網友回復:
以下代碼有助于根據 ID 值獲取輸出。
當然,我是用 Lambda 寫的。
var officeId = 1;
var query = context.Agencies // your starting point - table in the "from" statement
.Join(database.context.Usage, // the source table of the inner join
agency => agency.OfficeId, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
usage => usage.OfficeId , // Select the foreign key (the second part of the "on" clause)
(agency, usage) => new {Agency = agency, Usage = usage }) // selection
.Where(x => x.Agency.OfficeId == id); // where statement
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/414427.html
標籤:
