如何使用linq查询与外键关联的值并在listview中显示

时间:2013-09-11 16:27:07

标签: c# asp.net sql linq

我有一个数据库,其中有两个表MaleFemale都有int primary key with the name ID两个表都有一个外键,两个表的外键都在一个单独的名为RecommendFemale的表。

男表:

男:

[dbo].[Male] (
    [ID]            INT           IDENTITY (1, 1) NOT NULL,
    [Image]         VARCHAR (MAX) NULL,
    [Name]          VARCHAR (50)  NULL,
    [Age]           INT           NULL,
    CONSTRAINT [PK_Female] PRIMARY KEY CLUSTERED ([ID] ASC)
);

女:

 [dbo].[Female] (
        [ID]            INT           IDENTITY (1, 1) NOT NULL,
        [Image]         VARCHAR (MAX) NULL,
        [Name]          VARCHAR (50)  NULL,
        [Age]           INT           NULL,
        CONSTRAINT [PK_Female] PRIMARY KEY CLUSTERED ([ID] ASC)
    );

推荐:

[dbo].[RecommendFemale] (
    [ID]          INT IDENTITY (1, 1) NOT NULL,
    [RecommendTo] INT NOT NULL,
    [Recommend]   INT NOT NULL,
    CONSTRAINT [PK_RecommendFemale] PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [FK_Table_1_Female] FOREIGN KEY ([RecommendTo]) REFERENCES [dbo].[Female] ([ID]),
    CONSTRAINT [FK_Table_1_Male] FOREIGN KEY ([Recommend]) REFERENCES [dbo].[Male] ([ID])
);

RecommendTo是Female表ID的外键,而Recommend是Male表ID的外键值。

我的问题是我想在列表视图中显示与外键关联的value

示例:Recommend表在RecommendTo列中有多个外键值为Female,recommend列列表中包含男性表的值。

我想将与RecommendTo相关联的值显示到列表视图中,即ID 4在外键表中有多个值,我想在列表视图中显示与该单个数字关联的值,如何去做 ?

1 个答案:

答案 0 :(得分:1)

您想要在[男性]或[女性]表中选择特定记录的所有建议吗?

如果您不使用LINQ TO SQL,而是执行动态查询或编写存储过程,它将如下所示(查找[Female]表中的记录建议):

SELECT
    m.ID
    ,m.IMAGE
    ,m.NAME
    ,m.AGE
FROM [dbo].[Male] m
INNER JOIN [dbo].[RecommendFemale] rf ON rf.Recommend = m.ID
WHERE ft.RecommendTo = %FEMALE_ID%