简体   繁体   English

使用LINQ to SQL基于密钥连接两个表

[英]Joining Two Tables based upon a Key using LINQ to SQL

I've got Two tables Attribute(AID, Name, Description) AttributeVal(AID,Value) 我有两个表属性(AID,名称,描述)AttributeVal(AID,Value)

Now, Using LINQ I need to get the Name, Description and Value by joining these two tables. 现在,使用LINQ我需要通过连接这两个表来获取Name,Description和Value。 So, far I got here.. 所以,我到这儿了..

        var displayAttributeMap = dctx.Attributes.Join(dctx.AttributeDisplayNames, a => a.AttributeID, adn => adn.AttributeID, 
                                                        (a, adn) => new
                                                        {
                                                            AttributeName = a.Name,
                                                            AttributeDispName = adn.DisplayName
                                                        }
                                                       ).ToDictionary(a => a.AttributeName, a => a.AttributeDispName);

But here I don't know where to insert a condition on the foreign key, in my case it is Attribute ID. 但是在这里我不知道在外键上插入条件的位置,在我的例子中它是属性ID。 Am I missing something here or should I use LINQ directly? 我在这里遗漏了什么或者我应该直接使用LINQ吗?

From what I gather, you need the value AND the display name of the attribute put into a dictionary. 从我收集的内容中,您需要将值和显示在字典中的属性的显示名称。

All you need to do is add another join to your current query and change your select and ToDictionary around a bit. 您需要做的就是在当前查询中添加另一个连接,并稍微更改您的select和ToDictionary。 I find using the query syntax easier to read and use when dealing with joins. 我发现在处理连接时使用查询语法更容易阅读和使用。

(from attr in dctx.Attributes
    join attrDisplayName in dctx.AttributeDisplayNames on attr.AttributeID equals attrDisplayName.AttributeID
    join attrVal in dctx.AttributeVal on attr.AttributeID equals attrVal.AttributeID
select new
{
    AttributeName = attr.Name,
    AttributeDispName = attrDisplayName.DisplayName,
    AttributeID = attr.AttributeID,
    AttributeValue = attrVal.Value
}).ToDictionary(key => key.AttributeID, (value) => { return new { DisplayName = value.AttributeDispName, Value = value.AttributeValue };})

I haven't tested it but LinqPad is happy with the syntax, so I think it should work. 我没有测试过,但LinqPad对语法很满意,所以我认为它应该可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM