[英]using linq to get a single record from a table linked to another table
這個問題令人困惑,因為我真的不知道該怎么問。
無論如何,我有4個表,我需要進入TokenSetting表以獲取單個記錄。 我得到了公司代碼,我必須從那里旅行,並獲得我需要的其余信息。 而且由於每個公司都有多個公司結構,因此我必須首先獲得公司結構才能獲得分配給它的令牌。
這是布局:
這是我的代碼:
_currentcorp = (from c in _entities.Corporations
where c.CompanyCode == textBox_CompanyCode.Text
select c).FirstOrDefault();
if (_currentcorp == null)
{
errorProvider1.SetError(textBox_CompanyCode, "Invalid corporation.");
return;
}
var corpstructure = (from cs in _currentcorp.CorporationStructures
where cs.District == null &&
cs.Branch == null &&
cs.Region == null
select cs).FirstOrDefault();
if (corpstructure == null)
{
errorProvider1.SetError(textBox_CompanyCode, "Invalid corporation structure.");
return;
}
var tokensetting = (from ts in _currentcorp.Tokens
where ts.CorporationStructureId == corpstructure.CorporationStructureId
select ts.TokenSettings).FirstOrDefault();
即使我告訴它要獲得firstordefault,tokensetting又會變得無數。 我假設這是說在令牌上獲得firstordefault?
無論如何,即使令牌設置表是一對多表,令牌設置表中也應該只有1條記錄。 如何僅在此表上返回firstordefault?
====答案====
按照建議,我做了以下工作:
var tokensetting = (from ts in _currentcorp.Tokens
where ts.CorporationStructureId == corpstructure.CorporationStructureId
select ts.TokenSettings.FirstOrDefault()).FirstOrDefault();
我相信LINQ查詢返回的是IEnumerable
的IEnumerables
,因此第二個.FirstOrDefault()
應該會為您提供所需的內容。
第一個調用指定您想要LINQ查詢結果中的第一行,第二個調用指定您想要ts.TokenSettings
的第一個元素,該元素本身就是一個集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.