2012-03-26 104 views
0

我有兩個表代表混合物和混合物的組成部分。該表的佈局是這樣的:LINQ到SQL子選擇

Mixture table: 
MixtureID uniqueidentifier 
MixtureDescription varchar(50) 

Components table: 
ComponentID uniqueidentifier 
MixtureID uniqueidentifier (FK to previous table) 
ComponentName varchar(50) 
ComponentRatioPercentage int 

現在,我想要做的就是採取從用戶輸入組件名稱的列表,找到包含所有這些組件的任何混合物的ID的。

在SQL我會這麼像:

select distinct MixtureID 
from Mixture Mixture 
where exists (select ComponentName 
     from Components Components1 
     where Components1.MixtureID = Mixture.MixtureID and 
      Components1.ComponentDescription = 'SomeComponentName') 
     and exists (select ComponentName 
     from Components2 
     where Components2.MixtureID = Mixture.MixtureID and 
      Components2.ComponentDescription = 'SomeOtherComponentName') 
     and exists.... 

等,增添一分選的每個組件。

我該怎麼做這樣的linq到sql?在用戶完成輸入之前,要預先查找的組件數量不會被預先知道,儘管最多可以有10個。預先感謝!

+1

你嘗試過什麼嗎?如果是這樣,發佈它,我們可以更好地幫助你。 – 2012-03-26 22:37:41

回答

0
var components = new string[] {"SomeComponentName", "SomeOtherComponentName"}; 
var query = Mixtures.AsQueryable(); 
foreach (var component in components) 
{ 
    var tmpComponent = component; 
    query = query.Where(m => m.Components 
            .Any(c => t.ComponentDescription == tmpComponent) 
          ); 
} 

var mixturesIds = query.Select(m=>m.MixtureId).Distinct(); 
+0

謝謝,我會給它一個機會! – 2012-03-27 13:00:02