需要从一个表中获取所有记录,这些记录匹配从另一个表返回的值

时间:2013-12-10 18:29:42

标签: c# linq

在第一次执行搜索到另一个表之后,我正在尝试从一个表返回所有记录的查询。两个表中都有一个共同的字段。这是描述查找表的DDL:

CREATE TABLE [dbo].[ASICodesSubstanceType](
[SubstanceType] [tinyint] NOT NULL,
[SubstanceDesc] [varchar](50) NOT NULL,
[DisplayOrder] [tinyint] NULL,
CONSTRAINT [PK_ASICodesSubstanceType] PRIMARY KEY CLUSTERED 
(
[SubstanceType] ASC
)

这是数据表的DDL:

CREATE TABLE [dbo].[ASISubstanceUse](
[ClientNumber] [int] NOT NULL,
[CaseNumber] [tinyint] NOT NULL,
[Followup] [tinyint] NOT NULL,
[SubstanceType] [tinyint] NOT NULL,
[DaysUseLast30] [tinyint] NULL,
[LifeUseYears] [tinyint] NULL,
[Route] [tinyint] NULL,
[AgeOfFirstUse] [tinyint] NULL,
CONSTRAINT [PK_ASISubstanceUse] PRIMARY KEY NONCLUSTERED 
(
[ClientNumber] ASC,
[CaseNumber] ASC,
[Followup] ASC,
[SubstanceType] ASC
)

这是我为检索存储在数据表ASISubstanceUse表中的所有物质所做的工作:

//get all of the currently selected substance types
var selectedSubstances = asiContext.ASISubstanceUses.Where(c => c.ClientNumber == ClientNumber && c.CaseNumber == CaseNumber)
.Select<ASISubstanceUse, byte>(r => r.SubstanceType);

但这是下一步我不知道该怎么办。我想从ASICodesSubstanceType返回所有记录,这些记录与我在selectedSubstances中的记录相匹配。这是我到目前为止所得到的:

//get the records from the lookup table that match the selected substances
var selectedFromLookup = asiContext.ASICodesSubstanceTypes.Where(s => s.SubstanceType in selectedSubstances);

但这根本不起作用。我该怎么做我想做的事?

2 个答案:

答案 0 :(得分:1)

使用Any

var selectedFromLookup = asiContext.ASICodesSubstanceTypes
    .Where(s => selectedSubstances.Any(sel => sel == s.SubstanceType));

答案 1 :(得分:1)

这是你需要的吗?

int clientNumber = 0;
int caseNumber = 1;

var qry = from substance in ASICodesSubstanceTypes
        join uses in ASISubstanceUses on substance.SubstanceType equals uses.SubstanceType
        where uses.ClientNumber == clientNumber && uses.CaseNumber == caseNumber
        select substance;